Skip to content

Commit 4fe77a9

Browse files
committed
Pass options to json renderer
1 parent f6c5796 commit 4fe77a9

File tree

2 files changed

+20
-2
lines changed

2 files changed

+20
-2
lines changed

src/Renderer/Json.php

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,10 +36,13 @@
3636
*/
3737
class Json implements RendererInterface
3838
{
39+
const JSON_OPTIONS_KEY = 'jsonOptions';
40+
3941
public function render(ServerRequestInterface $request, ResponseInterface $response, array $options, $data): ResponseInterface
4042
{
4143
$response = $response->withHeader('Content-Type', 'application/json');
42-
$dataStr = json_encode($data);
44+
$opts = $options[static::JSON_OPTIONS_KEY] ?? 0;
45+
$dataStr = json_encode($data, $opts);
4346
if ($dataStr === false) {
4447
// Check for JSON error
4548
$err = json_last_error();
@@ -61,7 +64,8 @@ public function renderException(ServerRequestInterface $request, ResponseInterfa
6164
'message' => $exception->getMessage(),
6265
'details' => $exception->data
6366
];
64-
$response = $response->withBody(stream_for(json_encode($data)));
67+
$opts = $options[static::JSON_OPTIONS_KEY] ?? 0;
68+
$response = $response->withBody(stream_for(json_encode($data, $opts)));
6569
} else {
6670
$response = $response->withStatus(500);
6771
}

tests/Renderer/JsonTest.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,20 @@ public function testRenderOK()
4848
$this->assertSame('application/json', $response->getHeaderLine('Content-Type'));
4949
}
5050

51+
public function testRenderOKWithOpts()
52+
{
53+
$renderer = new Json();
54+
$request = new ServerRequest('GET', '/');
55+
$response = new Response();
56+
$data = ['foo' => 'bar'];
57+
58+
$response = $renderer->render($request, $response, [Json::JSON_OPTIONS_KEY => JSON_PRETTY_PRINT], $data);
59+
60+
$this->assertSame(200, $response->getStatusCode());
61+
$this->assertSame(json_encode($data, JSON_PRETTY_PRINT), $response->getBody()->getContents());
62+
$this->assertSame('application/json', $response->getHeaderLine('Content-Type'));
63+
}
64+
5165
public function testRenderKO()
5266
{
5367
$renderer = new Json();

0 commit comments

Comments
 (0)