8000 Fix problem with empty generator in StreamedJsonResponse · symfony/symfony@39bb6b6 · GitHub
[go: up one dir, main page]

Skip to content

Commit 39bb6b6

Browse files
alexander-schranznicolas-grekas
authored andcommitted
Fix problem with empty generator in StreamedJsonResponse
1 parent 398830c commit 39bb6b6

File tree

2 files changed

+25
-8
lines changed

2 files changed

+25
-8
lines changed

src/Symfony/Component/HttpFoundation/StreamedJsonResponse.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,10 @@ private function stream(): void
130130
echo json_encode($item, $jsonEncodingOptions);
131131
}
132132

133+
if ($isFirstItem) { // indicates that the generator was empty
134+
echo '[';
135+
}
136+
133137
echo '[' === $startTag ? ']' : '}';
134138
}
135139

src/Symfony/Component/HttpFoundation/Tests/StreamedJsonResponseTest.php

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,19 @@ public function testResponseSimpleList()
3030
$this->assertSame('{"_embedded":{"articles":["Article 1","Article 2","Article 3"],"news":["News 1","News 2","News 3"]}}', $content);
3131
}
3232

33+
public function testResponseEmptyList()
34+
{
35+
$content = $this->createSendResponse(
36+
[
37+
'_embedded' => [
38+
'articles< 10000 /span>' => $this->generatorSimple('Article', 0),
39+
],
40+
],
41+
);
42+
43+
$this->assertSame('{"_embedded":{"articles":[]}}', $content);
44+
}
45+
3346
public function testResponseObjectsList()
3447
{
3548
$content = $this->createSendResponse(
@@ -222,20 +235,20 @@ private function createSendResponse(array $data): string
222235
/**
223236
* @return \Generator<int, string>
224237
*/
225-
private function generatorSimple(string $test): \Generator
238+
private function generatorSimple(string $test, int $length = 3): \Generator
226239
{
227-
yield $test.' 1';
228-
yield $test.' 2';
229-
yield $test.' 3';
240+
for ($i = 1; $i <= $length; ++$i) {
241+
yield $test.' '.$i;
242+
}
230243
}
231244

232245
/**
233246
* @return \Generator<int, array{title: string}>
234247
*/
235-
private function generatorArray(string $test): \Generator
248+
private function generatorArray(string $test, int $length = 3): \Generator
236249
{
237-
yield ['title' => $test.' 1'];
238-
yield ['title' => $test.' 2'];
239-
yield ['title' => $test.' 3'];
250+
for ($i = 1; $i <= $length; ++$i) {
251+
yield ['title' => $test.' '.$i];
252+
}
240253
}
241254
}

0 commit comments

Comments
 (0)
0