Skip to content

Commit

Permalink
[Serializer] Add headers label support for CsvEncoder using `csv_he…
Browse files Browse the repository at this point in the history
…aders`
  • Loading branch information
Seb33300 committed May 18, 2024
1 parent 4bf657a commit c3f8df5
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 1 deletion.
1 change: 1 addition & 0 deletions src/Symfony/Component/Serializer/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ CHANGELOG
* Add `CamelCaseToSnakeCaseNameConverter::REQUIRE_SNAKE_CASE_PROPERTIES` context option
* Deprecate `AbstractNormalizerContextBuilder::withDefaultContructorArguments(?array $defaultContructorArguments)`, use `withDefaultConstructorArguments(?array $defaultConstructorArguments)` instead (note the missing `s` character in Contructor word in deprecated method)
* Add `XmlEncoder::CDATA_WRAPPING_PATTERN` context option
* Add headers label support for `CsvEncoder` using `csv_headers`

7.0
---
Expand Down
4 changes: 3 additions & 1 deletion src/Symfony/Component/Serializer/Encoder/CsvEncoder.php
Original file line number Diff line number Diff line change
Expand Up @@ -86,11 +86,13 @@ public function encode(mixed $data, string $format, array $context = []): string
}
unset($value);

$labels = array_flip($headers);
$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);
$labels = array_map(fn ($header) => is_string($labels[$header] ?? null) ? $labels[$header] : $header, $headers);
fputcsv($handle, $labels, $delimiter, $enclosure, $escapeChar);
if ("\n" !== $endOfLine && 0 === fseek($handle, -1, \SEEK_CUR)) {
fwrite($handle, $endOfLine);
}
Expand Down

0 comments on commit c3f8df5

Please sign in to comment.