Skip to content
This repository was archived by the owner on Jan 29, 2020. It is now read-only.

Commit bf3f448

Browse files
committed
Use unescaped slashes in encoded JSON by default
- Updated the default `$encodingOptions` to also include `JSON_UNESCAPED_SLASHES`, which is a sane default, and still complies with RFC 4627 (forward slash, or the solidus, does not need to be escaped).
1 parent 8cce62e commit bf3f448

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

src/Response/JsonResponse.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,14 +34,15 @@ class JsonResponse extends Response
3434
* - JSON_HEX_APOS
3535
* - JSON_HEX_AMP
3636
* - JSON_HEX_QUOT
37+
* - JSON_UNESCAPED_SLASHES
3738
*
3839
* @param mixed $data Data to convert to JSON.
3940
* @param int $status Integer status code for the response; 200 by default.
4041
* @param array $headers Array of headers to use at initialization.
4142
* @param int $encodingOptions JSON encoding options to use.
4243
* @throws InvalidArgumentException if unable to encode the $data to JSON.
4344
*/
44-
public function __construct($data, $status = 200, array $headers = [], $encodingOptions = 15)
45+
public function __construct($data, $status = 200, array $headers = [], $encodingOptions = 79)
4546
{
4647
$body = new Stream('php://temp', 'wb+');
4748
$body->write($this->jsonEncode($data, $encodingOptions));

test/Response/JsonResponseTest.php

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,4 +98,32 @@ public function testJsonErrorHandlingOfBadEmbeddedData()
9898
$this->setExpectedException('InvalidArgumentException', 'Unable to encode');
9999
new JsonResponse($data);
100100
}
101+
102+
public function valuesToJsonEncode()
103+
{
104+
return [
105+
'uri' => ['https://example.com/foo?bar=baz&baz=bat', 'uri'],
106+
'html' => ['<p class="test">content</p>', 'html'],
107+
'string' => ["Don't quote!", 'string'],
108+
];
109+
}
110+
111+
/**
112+
* @dataProvider valuesToJsonEncode
113+
*/
114+
public function testUsesSaneDefaultJsonEncodingFlags($value, $key)
115+
{
116+
$defaultFlags = JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_SLASHES;
117+
118+
$response = new JsonResponse([$key => $value]);
119+
$stream = $response->getBody();
120+
$contents = (string) $stream;
121+
122+
$expected = json_encode($value, $defaultFlags);
123+
$this->assertContains(
124+
$expected,
125+
$contents,
126+
sprintf('Did not encode %s properly; expected (%s), received (%s)', $key, $expected, $contents)
127+
);
128+
}
101129
}

0 commit comments

Comments
 (0)