[Serializer] CsvEncoder no header option (encode / decode)
This commit is contained in:
parent
f2590d196f
commit
0e63c61190
@ -29,6 +29,7 @@ class CsvEncoder implements EncoderInterface, DecoderInterface
|
||||
const HEADERS_KEY = 'csv_headers';
|
||||
const ESCAPE_FORMULAS_KEY = 'csv_escape_formulas';
|
||||
const AS_COLLECTION_KEY = 'as_collection';
|
||||
const NO_HEADERS_KEY = 'no_headers';
|
||||
|
||||
private $formulasStartCharacters = array('=', '-', '+', '@');
|
||||
private $defaultContext = array(
|
||||
@ -38,6 +39,7 @@ class CsvEncoder implements EncoderInterface, DecoderInterface
|
||||
self::ESCAPE_FORMULAS_KEY => false,
|
||||
self::HEADERS_KEY => array(),
|
||||
self::KEY_SEPARATOR_KEY => '.',
|
||||
self::NO_HEADERS_KEY => false,
|
||||
);
|
||||
|
||||
/**
|
||||
@ -95,7 +97,9 @@ class CsvEncoder implements EncoderInterface, DecoderInterface
|
||||
|
||||
$headers = array_merge(array_values($headers), array_diff($this->extractHeaders($data), $headers));
|
||||
|
||||
if (!($context[self::NO_HEADERS_KEY] ?? false)) {
|
||||
fputcsv($handle, $headers, $delimiter, $enclosure, $escapeChar);
|
||||
}
|
||||
|
||||
$headers = array_fill_keys($headers, '');
|
||||
foreach ($data as $row) {
|
||||
@ -139,6 +143,12 @@ class CsvEncoder implements EncoderInterface, DecoderInterface
|
||||
if (null === $headers) {
|
||||
$nbHeaders = $nbCols;
|
||||
|
||||
if ($context[self::NO_HEADERS_KEY] ?? false) {
|
||||
for ($i = 0; $i < $nbCols; ++$i) {
|
||||
$headers[] = array($i);
|
||||
}
|
||||
$headerCount = array_fill(0, $nbCols, 1);
|
||||
} else {
|
||||
foreach ($cols as $col) {
|
||||
$header = explode($keySeparator, $col);
|
||||
$headers[] = $header;
|
||||
@ -147,6 +157,7 @@ class CsvEncoder implements EncoderInterface, DecoderInterface
|
||||
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
$item = array();
|
||||
for ($i = 0; ($i < $nbCols) && ($i < $nbHeaders); ++$i) {
|
||||
|
@ -309,6 +309,18 @@ CSV
|
||||
)));
|
||||
}
|
||||
|
||||
public function testEncodeWithoutHeader()
|
||||
{
|
||||
$this->assertSame(<<<'CSV'
|
||||
a,b
|
||||
c,d
|
||||
|
||||
CSV
|
||||
, $this->encoder->encode(array(array('a', 'b'), array('c', 'd')), 'csv', array(
|
||||
CsvEncoder::NO_HEADERS_KEY => true,
|
||||
)));
|
||||
}
|
||||
|
||||
public function testSupportsDecoding()
|
||||
{
|
||||
$this->assertTrue($this->encoder->supportsDecoding('csv'));
|
||||
@ -480,4 +492,16 @@ CSV
|
||||
{
|
||||
$this->assertEquals(array(), $this->encoder->decode('', 'csv'));
|
||||
}
|
||||
|
||||
public function testDecodeWithoutHeader()
|
||||
{
|
||||
$this->assertEquals(array(array('a', 'b'), array('c', 'd')), $this->encoder->decode(<<<'CSV'
|
||||
a,b
|
||||
c,d
|
||||
|
||||
CSV
|
||||
, 'csv', array(
|
||||
CsvEncoder::NO_HEADERS_KEY => true,
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user