diff --git a/src/Symfony/Component/HttpFoundation/StreamedJsonResponse.php b/src/Symfony/Component/HttpFoundation/StreamedJsonResponse.php index 445bd77d794cb..cf858a5eb70a9 100644 --- a/src/Symfony/Component/HttpFoundation/StreamedJsonResponse.php +++ b/src/Symfony/Component/HttpFoundation/StreamedJsonResponse.php @@ -130,6 +130,10 @@ private function stream(): void echo json_encode($item, $jsonEncodingOptions); } + if ($isFirstItem) { // indicates that the generator was empty + echo '['; + } + echo '[' === $startTag ? ']' : '}'; } diff --git a/src/Symfony/Component/HttpFoundation/Tests/StreamedJsonResponseTest.php b/src/Symfony/Component/HttpFoundation/Tests/StreamedJsonResponseTest.php index e142672fd0658..046f7dae434f9 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/StreamedJsonResponseTest.php +++ b/src/Symfony/Component/HttpFoundation/Tests/StreamedJsonResponseTest.php @@ -30,6 +30,19 @@ public function testResponseSimpleList() $this->assertSame('{"_embedded":{"articles":["Article 1","Article 2","Article 3"],"news":["News 1","News 2","News 3"]}}', $content); } + public function testResponseEmptyList() + { + $content = $this->createSendResponse( + [ + '_embedded' => [ + 'articles' => $this->generatorSimple('Article', 0), + ], + ], + ); + + $this->assertSame('{"_embedded":{"articles":[]}}', $content); + } + public function testResponseObjectsList() { $content = $this->createSendResponse( @@ -222,20 +235,20 @@ private function createSendResponse(array $data): string /** * @return \Generator */ - private function generatorSimple(string $test): \Generator + private function generatorSimple(string $test, int $length = 3): \Generator { - yield $test.' 1'; - yield $test.' 2'; - yield $test.' 3'; + for ($i = 1; $i <= $length; ++$i) { + yield $test.' '.$i; + } } /** * @return \Generator */ - private function generatorArray(string $test): \Generator + private function generatorArray(string $test, int $length = 3): \Generator { - yield ['title' => $test.' 1']; - yield ['title' => $test.' 2']; - yield ['title' => $test.' 3']; + for ($i = 1; $i <= $length; ++$i) { + yield ['title' => $test.' '.$i]; + } } }