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 27, 2024
1 parent 4bf657a commit 5ecf425
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 1 deletion.
5 changes: 5 additions & 0 deletions src/Symfony/Component/Serializer/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
CHANGELOG
=========

7.2
---

* Add headers label support for `CsvEncoder` using `csv_headers`

7.1
---

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 5ecf425

Please sign in to comment.