Skip to content

Commit

Permalink
bug #45391 [Serializer] Ensuring end of line character apply with con…
Browse files Browse the repository at this point in the history
…structor settings in CSV encoder (bizley)

This PR was squashed before being merged into the 5.4 branch.

Discussion
----------

[Serializer] Ensuring end of line character apply with constructor settings in CSV encoder

| Q             | A
| ------------- | ---
| Branch?       | 5.4
| Bug fix?      | yes
| New feature?  | no
| Deprecations? | no
| Tickets       |
| License       | MIT
| Doc PR        |

While providing END_OF_LINE different than `\n` through constructor, context value was still used which ended in error if not present in context.

Commits
-------

e831aa7 [Serializer] Ensuring end of line character apply with constructor settings in CSV encoder
  • Loading branch information
nicolas-grekas committed Feb 11, 2022
2 parents 402fdd0 + e831aa7 commit c5be706
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 4 deletions.
9 changes: 5 additions & 4 deletions src/Symfony/Component/Serializer/Encoder/CsvEncoder.php
Original file line number Diff line number Diff line change
Expand Up @@ -94,19 +94,20 @@ public function encode($data, string $format, array $context = [])
unset($value);

$headers = array_merge(array_values($headers), array_diff($this->extractHeaders($data), $headers));
$endOfLine = $context[self::END_OF_LINE] ?? $this->defaultContext[self::END_OF_LINE];

if (!($context[self::NO_HEADERS_KEY] ?? $this->defaultContext[self::NO_HEADERS_KEY])) {
fputcsv($handle, $headers, $delimiter, $enclosure, $escapeChar);
if ("\n" !== ($context[self::END_OF_LINE] ?? $this->defaultContext[self::END_OF_LINE]) && 0 === fseek($handle, -1, \SEEK_CUR)) {
fwrite($handle, $context[self::END_OF_LINE]);
if ("\n" !== $endOfLine && 0 === fseek($handle, -1, \SEEK_CUR)) {
fwrite($handle, $endOfLine);
}
}

$headers = array_fill_keys($headers, '');
foreach ($data as $row) {
fputcsv($handle, array_replace($headers, $row), $delimiter, $enclosure, $escapeChar);
if ("\n" !== ($context[self::END_OF_LINE] ?? $this->defaultContext[self::END_OF_LINE]) && 0 === fseek($handle, -1, \SEEK_CUR)) {
fwrite($handle, $context[self::END_OF_LINE]);
if ("\n" !== $endOfLine && 0 === fseek($handle, -1, \SEEK_CUR)) {
fwrite($handle, $endOfLine);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -697,4 +697,12 @@ public function testEndOfLine()

$this->assertSame("foo,bar\r\nhello,test\r\n", $this->encoder->encode($value, 'csv', [CsvEncoder::END_OF_LINE => "\r\n"]));
}

public function testEndOfLinePassedInConstructor()
{
$value = ['foo' => 'hello', 'bar' => 'test'];

$encoder = new CsvEncoder([CsvEncoder::END_OF_LINE => "\r\n"]);
$this->assertSame("foo,bar\r\nhello,test\r\n", $encoder->encode($value, 'csv'));
}
}

0 comments on commit c5be706

Please sign in to comment.