@@ -25,6 +25,7 @@ class CsvEncoder implements EncoderInterface, DecoderInterface
25
25
const ENCLOSURE_KEY = 'csv_enclosure ' ;
26
26
const ESCAPE_CHAR_KEY = 'csv_escape_char ' ;
27
27
const KEY_SEPARATOR_KEY = 'csv_key_separator ' ;
28
+ const HEADERS_KEY = 'csv_headers ' ;
28
29
29
30
private $ delimiter ;
30
31
private $ enclosure ;
@@ -69,7 +70,7 @@ public function encode($data, $format, array $context = array())
69
70
}
70
71
}
71
72
72
- list ($ delimiter , $ enclosure , $ escapeChar , $ keySeparator ) = $ this ->getCsvOptions ($ context );
73
+ list ($ delimiter , $ enclosure , $ escapeChar , $ keySeparator, $ headers ) = $ this ->getCsvOptions ($ context );
73
74
74
75
foreach ($ data as &$ value ) {
75
76
$ flattened = array ();
@@ -78,7 +79,7 @@ public function encode($data, $format, array $context = array())
78
79
}
79
80
unset($ value );
80
81
81
- $ headers = $ this ->extractHeaders ($ data );
82
+ $ headers = array_merge ( array_values ( $ headers ), array_diff ( $ this ->extractHeaders ($ data), $ headers ) );
82
83
83
84
fputcsv ($ handle , $ headers , $ delimiter , $ enclosure , $ escapeChar );
84
85
@@ -195,8 +196,13 @@ protected function getCsvOptions(array $context)
195
196
$ enclosure = isset ($ context [self ::ENCLOSURE_KEY ]) ? $ context [self ::ENCLOSURE_KEY ] : $ this ->enclosure ;
196
197
$ escapeChar = isset ($ context [self ::ESCAPE_CHAR_KEY ]) ? $ context [self ::ESCAPE_CHAR_KEY ] : $ this ->escapeChar ;
197
198
$ keySeparator = isset ($ context [self ::KEY_SEPARATOR_KEY ]) ? $ context [self ::KEY_SEPARATOR_KEY ] : $ this ->keySeparator ;
199
+ $ headers = isset ($ context [self ::HEADERS_KEY ]) ? $ context [self ::HEADERS_KEY ] : array ();
200
+
201
+ if (!is_array ($ headers )) {
202
+ throw new InvalidArgumentException (sprintf ('The "%s" context variable must be an array or null, given "%s". ' , self ::HEADERS_KEY , gettype ($ headers )));
203
+ }
198
204
199
- return array ($ delimiter , $ enclosure , $ escapeChar , $ keySeparator );
205
+ return array ($ delimiter , $ enclosure , $ escapeChar , $ keySeparator, $ headers );
200
206
}
201
207
202
208
/**
0 commit comments