Skip to content

Commit ec4e5a7

Browse files
bug #62407 [FrameworkBundle] work around limitation in JsonResponse when the data is null (xabbuh)
This PR was merged into the 6.4 branch. Discussion ---------- [FrameworkBundle] work around limitation in `JsonResponse` when the data is `null` | Q | A | ------------- | --- | Branch? | 6.4 | Bug fix? | yes | New feature? | no | Deprecations? | no | Issues | Fix #62404 | License | MIT I did abstain from fixing this in `JsonResponse` since https://github.com/symfony/symfony/blob/6769c4c670736adad5d77fe02c25f313e10971b6/src/Symfony/Component/HttpFoundation/JsonResponse.php#L47 has been there for years since 2d07a17 Commits ------- c0287d5 work around limitation in JsonResponse when the data is null
2 parents b36f587 + c0287d5 commit ec4e5a7

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

src/Symfony/Bundle/FrameworkBundle/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

src/Symfony/Bundle/FrameworkBundle/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)