diff --git a/src/Symfony/Component/Serializer/Encoder/CsvEncoder.php b/src/Symfony/Component/Serializer/Encoder/CsvEncoder.php index 747178953fee..4c518145612d 100644 --- a/src/Symfony/Component/Serializer/Encoder/CsvEncoder.php +++ b/src/Symfony/Component/Serializer/Encoder/CsvEncoder.php @@ -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); } } diff --git a/src/Symfony/Component/Serializer/Tests/Encoder/CsvEncoderTest.php b/src/Symfony/Component/Serializer/Tests/Encoder/CsvEncoderTest.php index b28667b2e19d..2aa48f5ee347 100644 --- a/src/Symfony/Component/Serializer/Tests/Encoder/CsvEncoderTest.php +++ b/src/Symfony/Component/Serializer/Tests/Encoder/CsvEncoderTest.php @@ -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')); + } }