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

[8.x] Introduce JsString for encoding data to use in JavaScript #39460

Merged
merged 4 commits into from
Nov 5, 2021
Merged
Show file tree
Hide file tree
Changes from 2 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
29 changes: 0 additions & 29 deletions src/Illuminate/Support/Js.php

This file was deleted.

143 changes: 143 additions & 0 deletions src/Illuminate/Support/JsString.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
<?php

namespace Illuminate\Support;

use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Contracts\Support\Jsonable;
use JsonSerializable;

class JsString implements Htmlable
{
/**
* Flags that must always be used when encoding to JSON for JsString.
*
* @var int
*/
protected const REQUIRED_FLAGS = JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT | JSON_THROW_ON_ERROR;

/**
* The javascript string.
*
* @var string
*/
protected $js;

/**
* Create a new JsString from data.
*
* @param mixed $data
* @param int $flags
* @param int $depth
* @return static
*
* @throws \JsonException
*/
public static function from($data, $flags = 0, $depth = 512)
{
return new static($data, $flags, $depth);
}

/**
* Create a new JsString.
*
* @param mixed $data
* @param int|null $flags
* @param int $depth
* @return void
*
* @throws \JsonException
*/
public function __construct($data, $flags = 0, $depth = 512)
{
$this->js = $this->convertDataToJavaScriptExpression($data, $flags, $depth);
}

/**
* Get string representation of data for use in HTML.
*
* @return string
*/
public function toHtml()
{
return $this->js;
}

/**
* Get string representation of data for use in HTML.
*
* @return string
*/
public function __toString()
{
return $this->toHtml();
}

/**
* Convert data to a JavaScript expression.
*
* @param mixed $data
* @param int $flags
* @param int $depth
* @return string
*
* @throws \JsonException
*/
protected function convertDataToJavaScriptExpression($data, $flags = 0, $depth = 512)
{
$json = $this->jsonEncode($data, $flags, $depth);

if (is_string($data)) {
return "'".substr($json, 1, '-1')."'";
inxilpro marked this conversation as resolved.
Show resolved Hide resolved
}

return $this->convertJsonToJavaScriptExpression($json, $flags);
}

/**
* Encode data as JSON.
*
* @param mixed $data
* @param int $flags
* @param int $depth
* @return string
*
* @throws \JsonException
*/
protected function jsonEncode($data, $flags = 0, $depth = 512)
{
if ($data instanceof Jsonable) {
return $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);
}

/**
* Convert JSON to a JavaScript expression.
*
* @param string $json
* @param int $flags
* @return string
*
* @throws \JsonException
*/
protected function convertJsonToJavaScriptExpression($json, $flags = 0)
{
if ('[]' === $json || '{}' === $json) {
return $json;
}

if (Str::startsWith($json, ['"', '{', '['])) {
$json = json_encode($json, $flags | static::REQUIRED_FLAGS);

return "JSON.parse('".substr($json, 1, -1)."')";
}

return $json;
}
}
124 changes: 124 additions & 0 deletions tests/Support/SupportJsStringTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
<?php

namespace Illuminate\Tests\Support;

use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Contracts\Support\Jsonable;
use Illuminate\Support\JsString;
use JsonSerializable;
use PHPUnit\Framework\TestCase;

class SupportJsStringTest extends TestCase
{
public function testScalars()
{
$this->assertEquals('false', (string) JsString::from(false));
$this->assertEquals('true', (string) JsString::from(true));
$this->assertEquals('1', (string) JsString::from(1));
$this->assertEquals('1.1', (string) JsString::from(1.1));
$this->assertEquals(
"'\\u003Cdiv class=\\u0022foo\\u0022\\u003E\\u0027quoted html\\u0027\\u003C\\/div\\u003E'",
(string) JsString::from('<div class="foo">\'quoted html\'</div>')
);
}

public function testArrays()
{
$this->assertEquals(
"JSON.parse('[\\u0022hello\\u0022,\\u0022world\\u0022]')",
(string) JsString::from(['hello', 'world'])
);

$this->assertEquals(
"JSON.parse('{\\u0022foo\\u0022:\\u0022hello\\u0022,\\u0022bar\\u0022:\\u0022world\\u0022}')",
(string) JsString::from(['foo' => 'hello', 'bar' => 'world'])
);
}

public function testObjects()
{
$this->assertEquals(
"JSON.parse('{\\u0022foo\\u0022:\\u0022hello\\u0022,\\u0022bar\\u0022:\\u0022world\\u0022}')",
(string) JsString::from((object) ['foo' => 'hello', 'bar' => 'world'])
);
}

public function testJsonSerializable()
{
// JsonSerializable should take precedence over Arrayable, so we'll
// implement both and make sure the correct data is used.
$data = new class() implements JsonSerializable, Arrayable
{
public $foo = 'not hello';

public $bar = 'not world';

public function jsonSerialize()
{
return ['foo' => 'hello', 'bar' => 'world'];
}

public function toArray()
{
return ['foo' => 'not hello', 'bar' => 'not world'];
}
};

$this->assertEquals(
"JSON.parse('{\\u0022foo\\u0022:\\u0022hello\\u0022,\\u0022bar\\u0022:\\u0022world\\u0022}')",
(string) JsString::from($data)
);
}

public function testJsonable()
{
// Jsonable should take precedence over JsonSerializable and Arrayable, so we'll
// implement all three and make sure the correct data is used.
$data = new class() implements Jsonable, JsonSerializable, Arrayable
{
public $foo = 'not hello';

public $bar = 'not world';

public function toJson($options = 0)
{
return json_encode(['foo' => 'hello', 'bar' => 'world'], $options);
}

public function jsonSerialize()
{
return ['foo' => 'not hello', 'bar' => 'not world'];
}

public function toArray()
{
return ['foo' => 'not hello', 'bar' => 'not world'];
}
};

$this->assertEquals(
"JSON.parse('{\\u0022foo\\u0022:\\u0022hello\\u0022,\\u0022bar\\u0022:\\u0022world\\u0022}')",
(string) JsString::from($data)
);
}

public function testArrayable()
{
$data = new class() implements Arrayable
{
public $foo = 'not hello';

public $bar = 'not world';

public function toArray()
{
return ['foo' => 'hello', 'bar' => 'world'];
}
};

$this->assertEquals(
"JSON.parse('{\\u0022foo\\u0022:\\u0022hello\\u0022,\\u0022bar\\u0022:\\u0022world\\u0022}')",
(string) JsString::from($data)
);
}
}
17 changes: 0 additions & 17 deletions tests/Support/SupportJsTest.php

This file was deleted.