Skip to content

Commit f429789

Browse files
tanthammardriesvintstaylorotwell
authored
[8.x] Add js() helper (#39389)
* Add js() helper * update docBlock to pass all tests * Fix failing StyleCI * Update helpers.php * Update helpers.php * add tests * formatting * move test * fix sort * Fix: Support Js string, escaping characters. * Rename Json blade directives and helpers * update BladeJsonTest * second try with BladeJsonTest * Fix StyleCI * Reverting back to Js:from with changes suggested by @derekmd * fixing tests backslash Co-authored-by: Dries Vints <[email protected]> Co-authored-by: Taylor Otwell <[email protected]>
1 parent 14f84b0 commit f429789

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

src/Illuminate/Support/Js.php

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
<?php
2+
3+
namespace Illuminate\Support;
4+
5+
class Js
6+
{
7+
/**
8+
* Convert an expression into a valid JavaScript object, JSON string, or string.
9+
*
10+
* @param mixed $expression
11+
* @param int|null $options
12+
* @param int $depth
13+
* @return string
14+
*/
15+
public static function from($expression, $options = null, $depth = 512)
16+
{
17+
if (is_object($expression) || is_array($expression)) {
18+
$base64 = base64_encode(json_encode($expression, $options, $depth));
19+
20+
return "JSON.parse(atob('{$base64}'))";
21+
}
22+
23+
if (is_string($expression)) {
24+
return "'".str_replace("'", "\'", str_replace('\\', '\\\\', $expression))."'";
25+
}
26+
27+
return json_encode($expression, $options, $depth);
28+
}
29+
}

tests/Support/SupportJsTest.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
<?php
2+
3+
namespace Illuminate\Tests\Support;
4+
5+
use Illuminate\Support\Js;
6+
use PHPUnit\Framework\TestCase;
7+
8+
class SupportJsTest extends TestCase
9+
{
10+
public function testJsFrom()
11+
{
12+
$this->assertEquals("'hey'", Js::from('hey'));
13+
$this->assertEquals("'don\'t mess with my path\\\path'", Js::from("don't mess with my path\path"));
14+
$this->assertEquals("JSON.parse(atob('eyJoZXkiOiJ0aGVyZSJ9'))", Js::from(['hey' => 'there']));
15+
$this->assertEquals("JSON.parse(atob('WyJoZXkiLCJ0aGVyZSJd'))", Js::from(['hey', 'there']));
16+
}
17+
}

0 commit comments

Comments
 (0)