Thanks to visit codestin.com
Credit goes to github.com

Skip to content

[HttpFoundation] Fix problem with empty generator in StreamedJsonResponse #50331

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/Symfony/Component/HttpFoundation/StreamedJsonResponse.php
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,10 @@ private function stream(): void
echo json_encode($item, $jsonEncodingOptions);
}

if ($isFirstItem) { // indicates that the generator was empty
echo '[';
}

echo '[' === $startTag ? ']' : '}';
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -222,20 +235,20 @@ private function createSendResponse(array $data): string
/**
* @return \Generator<int, string>
*/
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<int, array{title: string}>
*/
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];
}
}
}