Skip to content

[Serializer] Prevent Cannot traverse an already closed generator error by materializing Traversable input #60260

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
merged 1 commit into from
May 12, 2025
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/Serializer/Encoder/CsvEncoder.php
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,10 @@ public function encode(mixed $data, string $format, array $context = []): string
} elseif (empty($data)) {
$data = [[]];
} else {
if ($data instanceof \Traversable) {
// Generators can only be iterated once — convert to array to allow multiple traversals
$data = iterator_to_array($data);
}
// Sequential arrays of arrays are considered as collections
$i = 0;
foreach ($data as $key => $value) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -710,4 +710,28 @@ public function testEndOfLinePassedInConstructor()
$encoder = new CsvEncoder([CsvEncoder::END_OF_LINE => "\r\n"]);
$this->assertSame("foo,bar\r\nhello,test\r\n", $encoder->encode($value, 'csv'));
}

/** @dataProvider provideIterable */
public function testIterable(mixed $data)
{
$this->assertEquals(<<<'CSV'
foo,bar
hello,"hey ho"
hi,"let's go"

CSV, $this->encoder->encode($data, 'csv'));
}

public static function provideIterable()
{
$data = [
['foo' => 'hello', 'bar' => 'hey ho'],
['foo' => 'hi', 'bar' => 'let\'s go'],
];

yield 'array' => [$data];
yield 'array iterator' => [new \ArrayIterator($data)];
yield 'iterator aggregate' => [new \IteratorIterator(new \ArrayIterator($data))];
yield 'generator' => [(fn (): \Generator => yield from $data)()];
}
}
Loading