@@ -28,6 +28,7 @@ class CsvEncoder implements EncoderInterface, DecoderInterface
28
28
public const ESCAPE_CHAR_KEY = 'csv_escape_char ' ;
29
29
public const KEY_SEPARATOR_KEY = 'csv_key_separator ' ;
30
30
public const HEADERS_KEY = 'csv_headers ' ;
31
+ public const CSV_FILTER_VALUES_BY_HEADERS_KEY = 'csv_filter_values_by_headers ' ;
31
32
public const ESCAPE_FORMULAS_KEY = 'csv_escape_formulas ' ;
32
33
public const AS_COLLECTION_KEY = 'as_collection ' ;
33
34
public const NO_HEADERS_KEY = 'no_headers ' ;
@@ -47,6 +48,7 @@ class CsvEncoder implements EncoderInterface, DecoderInterface
47
48
self ::HEADERS_KEY => [],
48
49
self ::KEY_SEPARATOR_KEY => '. ' ,
49
50
self ::NO_HEADERS_KEY => false ,
51
+ self ::CSV_FILTER_VALUES_BY_HEADERS_KEY => false ,
50
52
self ::AS_COLLECTION_KEY => true ,
51
53
self ::OUTPUT_UTF8_BOM_KEY => false ,
52
54
];
@@ -86,10 +88,17 @@ public function encode(mixed $data, string $format, array $context = []): string
86
88
}
87
89
unset($ value );
88
90
89
- $ headers = array_merge (array_values ($ headers ), array_diff ($ this ->extractHeaders ($ data ), $ headers ));
91
+ $ noHeaders = $ context [self ::NO_HEADERS_KEY ] ?? $ this ->defaultContext [self ::NO_HEADERS_KEY ];
92
+ $ filterByHeaders = !$ noHeaders ? $ context [self ::CSV_FILTER_VALUES_BY_HEADERS_KEY ] ??
93
+ $ this ->defaultContext [self ::CSV_FILTER_VALUES_BY_HEADERS_KEY ] : false ;
94
+
95
+ $ headers = array_merge (
96
+ array_values ($ headers ),
97
+ $ filterByHeaders ? [] : array_diff ($ this ->extractHeaders ($ data ), $ headers )
98
+ );
90
99
$ endOfLine = $ context [self ::END_OF_LINE ] ?? $ this ->defaultContext [self ::END_OF_LINE ];
91
100
92
- if (!($ context [ self :: NO_HEADERS_KEY ] ?? $ this -> defaultContext [ self :: NO_HEADERS_KEY ] )) {
101
+ if (!($ noHeaders )) {
93
102
fputcsv ($ handle , $ headers , $ delimiter , $ enclosure , $ escapeChar );
94
103
if ("\n" !== $ endOfLine && 0 === fseek ($ handle , -1 , \SEEK_CUR )) {
95
104
fwrite ($ handle , $ endOfLine );
@@ -98,7 +107,9 @@ public function encode(mixed $data, string $format, array $context = []): string
98
107
99
108
$ headers = array_fill_keys ($ headers , '' );
100
109
foreach ($ data as $ row ) {
101
- fputcsv ($ handle , array_replace ($ headers , $ row ), $ delimiter , $ enclosure , $ escapeChar );
110
+ $ fields = $ filterByHeaders ? array_replace ($ headers , array_intersect_key ($ row , $ headers )) :
111
+ array_replace ($ headers , $ row );
112
+ fputcsv ($ handle , $ fields , $ delimiter , $ enclosure , $ escapeChar );
102
113
if ("\n" !== $ endOfLine && 0 === fseek ($ handle , -1 , \SEEK_CUR )) {
103
114
fwrite ($ handle , $ endOfLine );
104
115
}
0 commit comments