Skip to content

Commit

Permalink
[Serializer] Handle true/false/null appropriately in CSV encoder
Browse files Browse the repository at this point in the history
  • Loading branch information
battye committed Jun 13, 2019
1 parent 7a6ce5f commit b3ce057
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 1 deletion.
27 changes: 26 additions & 1 deletion src/Symfony/Component/Serializer/Encoder/CsvEncoder.php
Expand Up @@ -189,11 +189,36 @@ private function flatten(array $array, array &$result, $keySeparator, $parentKey
if (\is_array($value)) {
$this->flatten($value, $result, $keySeparator, $parentKey.$key.$keySeparator);
} else {
$result[$parentKey.$key] = $value;
$result[$parentKey.$key] = $this->cleanValueByType($value);
}
}
}

/**
* Ensures an actual value is used instead of a blank value when dealing
* with true, false and null (like a nullable bool in a database).
*
* @param string $value
*
* @return string
*/
private function cleanValueByType($value)
{
$clean = $value;

if (false === $value) {
$clean = 0;
} elseif (null === $value) {
// fputcsv will enclose a space
// https://github.com/php/php-src/blob/master/ext/standard/file.c
$clean = ' ';
} elseif (true === $value) {
$clean = 1;
}

return $clean;
}

private function getCsvOptions(array $context)
{
$delimiter = isset($context[self::DELIMITER_KEY]) ? $context[self::DELIMITER_KEY] : $this->delimiter;
Expand Down
19 changes: 19 additions & 0 deletions src/Symfony/Component/Serializer/Tests/Encoder/CsvEncoderTest.php
Expand Up @@ -29,6 +29,25 @@ protected function setUp()
$this->encoder = new CsvEncoder();
}

public function testTrueFalseNullValues()
{
$data = [
'string' => 'foo',
'int' => 2,
'false' => false,
'true' => true,
'null' => null,
];

// Check that true, false and null are appropriately handled
$this->assertEquals(<<<'CSV'
string,int,false,true,null
foo,2,0,1," "
CSV
, $this->encoder->encode($data, 'csv'));
}

public function testSupportEncoding()
{
$this->assertTrue($this->encoder->supportsEncoding('csv'));
Expand Down

0 comments on commit b3ce057

Please sign in to comment.