Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[12.x] Switch Js::encode() to return HtmlString #50551

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions src/Illuminate/Support/Js.php
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ protected function convertDataToJavaScriptExpression($data, $flags = 0, $depth =
$data = $data->value;
}

$json = static::encode($data, $flags, $depth);
$json = (string) static::encode($data, $flags, $depth);

if (is_string($data)) {
return "'".substr($json, 1, -1)."'";
Expand All @@ -90,21 +90,21 @@ protected function convertDataToJavaScriptExpression($data, $flags = 0, $depth =
* @param mixed $data
* @param int $flags
* @param int $depth
* @return string
* @return \Illuminate\Contracts\Support\Htmlable
*
* @throws \JsonException
*/
public static function encode($data, $flags = 0, $depth = 512)
public static function encode($data, $flags = 0, $depth = 512): Htmlable
{
if ($data instanceof Jsonable) {
return $data->toJson($flags | static::REQUIRED_FLAGS);
return new HtmlString($data->toJson($flags | static::REQUIRED_FLAGS));
}

if ($data instanceof Arrayable && ! ($data instanceof JsonSerializable)) {
$data = $data->toArray();
}

return json_encode($data, $flags | static::REQUIRED_FLAGS, $depth);
return new HtmlString(json_encode($data, $flags | static::REQUIRED_FLAGS, $depth));
}

/**
Expand Down
12 changes: 12 additions & 0 deletions tests/Support/SupportJsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Contracts\Support\Jsonable;
use Illuminate\Support\HtmlString;
use Illuminate\Support\Js;
use Illuminate\Tests\Support\Fixtures\IntBackedEnum;
use Illuminate\Tests\Support\Fixtures\StringBackedEnum;
Expand Down Expand Up @@ -130,4 +131,15 @@ public function testBackedEnums()
$this->assertSame('2', (string) Js::from(IntBackedEnum::TWO));
$this->assertSame("'Hello world'", (string) Js::from(StringBackedEnum::HELLO_WORLD));
}

public function testEncode()
{
$json = Js::encode(['foo' => 'hello', 'bar' => 'world']);

$this->assertInstanceOf(HtmlString::class, $json);
$this->assertEquals(
'{"foo":"hello","bar":"world"}',
(string) $json
);
}
}
Loading