Skip to content

Commit 31d5fe6

Browse files
Bizleynicolas-grekas
authored andcommitted
[Serializer] Ensuring end of line character apply with constructor settings in CSV encoder
1 parent 5d58faa commit 31d5fe6

File tree

2 files changed

+13
-4
lines changed

2 files changed

+13
-4
lines changed

Encoder/CsvEncoder.php

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -94,19 +94,20 @@ public function encode($data, string $format, array $context = [])
9494
unset($value);
9595

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

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

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

Tests/Encoder/CsvEncoderTest.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -697,4 +697,12 @@ public function testEndOfLine()
697697

698698
$this->assertSame("foo,bar\r\nhello,test\r\n", $this->encoder->encode($value, 'csv', [CsvEncoder::END_OF_LINE => "\r\n"]));
699699
}
700+
701+
public function testEndOfLinePassedInConstructor()
702+
{
703+
$value = ['foo' => 'hello', 'bar' => 'test'];
704+
705+
$encoder = new CsvEncoder([CsvEncoder::END_OF_LINE => "\r\n"]);
706+
$this->assertSame("foo,bar\r\nhello,test\r\n", $encoder->encode($value, 'csv'));
707+
}
700708
}

0 commit comments

Comments
 (0)