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