Skip to content

Commit 805dd49

Browse files
committed
[Serializer] Handle true/false/null appropriately in CSV encoder
1 parent 7a6ce5f commit 805dd49

File tree

2 files changed

+47
-1
lines changed

2 files changed

+47
-1
lines changed

src/Symfony/Component/Serializer/Encoder/CsvEncoder.php

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -189,11 +189,38 @@ private function flatten(array $array, array &$result, $keySeparator, $parentKey
189189
if (\is_array($value)) {
190190
$this->flatten($value, $result, $keySeparator, $parentKey.$key.$keySeparator);
191191
} else {
192-
$result[$parentKey.$key] = $value;
192+
$result[$parentKey.$key] = $this->cleanValueByType($value);
193193
}
194194
}
195195
}
196196

197+
/**
198+
* Ensures an actual value is used instead of a blank value when dealing
199+
* with true, false and null (like a nullable bool in a database).
200+
*
201+
* @param string $value
202+
*
203+
* @return string|int
204+
*/
205+
private function cleanValueByType($value)
206+
{
207+
if (false === $value) {
208+
return 0;
209+
}
210+
211+
if (null === $value) {
212+
// fputcsv will enclose a space
213+
// https://github.com/php/php-src/blob/master/ext/standard/file.c
214+
return ' ';
215+
}
216+
217+
if (true === $value) {
218+
return 1;
219+
}
220+
221+
return $value;
222+
}
223+
197224
private function getCsvOptions(array $context)
198225
{
199226
$delimiter = isset($context[self::DELIMITER_KEY]) ? $context[self::DELIMITER_KEY] : $this->delimiter;

src/Symfony/Component/Serializer/Tests/Encoder/CsvEncoderTest.php

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,25 @@ protected function setUp()
2929
$this->encoder = new CsvEncoder();
3030
}
3131

32+
public function testTrueFalseNullValues()
33+
{
34+
$data = [
35+
'string' => 'foo',
36+
'int' => 2,
37+
'false' => false,
38+
'true' => true,
39+
'null' => null,
40+
];
41+
42+
// Check that true, false and null are appropriately handled
43+
$this->assertEquals(<<<'CSV'
44+
string,int,false,true,null
45+
foo,2,0,1," "
46+
47+
CSV
48+
, $this->encoder->encode($data, 'csv'));
49+
}
50+
3251
public function testSupportEncoding()
3352
{
3453
$this->assertTrue($this->encoder->supportsEncoding('csv'));

0 commit comments

Comments
 (0)