@@ -26,6 +26,7 @@ class CsvEncoder implements EncoderInterface, DecoderInterface
2626 const ENCLOSURE_KEY = 'csv_enclosure ' ;
2727 const ESCAPE_CHAR_KEY = 'csv_escape_char ' ;
2828 const KEY_SEPARATOR_KEY = 'csv_key_separator ' ;
29+ const HEADERS_KEY = 'csv_headers ' ;
2930
3031 private $ delimiter ;
3132 private $ enclosure ;
@@ -70,7 +71,7 @@ public function encode($data, $format, array $context = array())
7071 }
7172 }
7273
73- list ($ delimiter , $ enclosure , $ escapeChar , $ keySeparator ) = $ this ->getCsvOptions ($ context );
74+ list ($ delimiter , $ enclosure , $ escapeChar , $ keySeparator, $ headers ) = $ this ->getCsvOptions ($ context );
7475
7576 foreach ($ data as &$ value ) {
7677 $ flattened = array ();
@@ -79,7 +80,7 @@ public function encode($data, $format, array $context = array())
7980 }
8081 unset($ value );
8182
82- $ headers = $ this ->extractHeaders ($ data );
83+ $ headers = array_merge ( array_values ( $ headers ), array_diff ( $ this ->extractHeaders ($ data), $ headers ) );
8384
8485 fputcsv ($ handle , $ headers , $ delimiter , $ enclosure , $ escapeChar );
8586
@@ -196,8 +197,13 @@ protected function getCsvOptions(array $context)
196197 $ enclosure = isset ($ context [self ::ENCLOSURE_KEY ]) ? $ context [self ::ENCLOSURE_KEY ] : $ this ->enclosure ;
197198 $ escapeChar = isset ($ context [self ::ESCAPE_CHAR_KEY ]) ? $ context [self ::ESCAPE_CHAR_KEY ] : $ this ->escapeChar ;
198199 $ 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+ }
199205
200- return array ($ delimiter , $ enclosure , $ escapeChar , $ keySeparator );
206+ return array ($ delimiter , $ enclosure , $ escapeChar , $ keySeparator, $ headers );
201207 }
202208
203209 /**
0 commit comments