Skip to content

Commit 4e623d4

Browse files
committed
work around limitation in JsonResponse when the data is null
1 parent ee58c2a commit 4e623d4

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

Controller/AbstractController.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,10 @@ protected function json(mixed $data, int $status = 200, array $headers = [], arr
157157
return new JsonResponse($json, $status, $headers, true);
158158
}
159159

160+
if (null === $data) {
161+
return new JsonResponse('null', $status, $headers, true);
162+
}
163+
160164
return new JsonResponse($data, $status, $headers);
161165
}
162166

Tests/Controller/AbstractControllerTest.php

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -224,6 +224,37 @@ public function testJsonWithSerializerContextOverride()
224224
$this->assertEquals('{}', $response->getContent());
225225
}
226226

227+
public function testJsonNull()
228+
{
229+
$controller = $this->createController();
230+
$controller->setContainer(new Container());
231+
232+
$response = $controller->json(null);
233+
$this->assertInstanceOf(JsonResponse::class, $response);
234+
$this->assertSame('null', $response->getContent());
235+
}
236+
237+
public function testJsonNullWithSerializer()
238+
{
239+
$container = new Container();
240+
241+
$serializer = $this->createMock(SerializerInterface::class);
242+
$serializer
243+
->expects($this->once())
244+
->method('serialize')
245+
->with(null, 'json', ['json_encode_options' => JsonResponse::DEFAULT_ENCODING_OPTIONS])
246+
->willReturn('null');
247+
248+
$container->set('serializer', $serializer);
249+
250+
$controller = $this->createController();
251+
$controller->setContainer($container);
252+
253+
$response = $controller->json(null);
254+
$this->assertInstanceOf(JsonResponse::class, $response);
255+
$this->assertSame('null', $response->getContent());
256+
}
257+
227258
public function testFile()
228259
{
229260
$container = new Container();

0 commit comments

Comments
 (0)