Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit805dd49

Browse files
committed
[Serializer] Handle true/false/null appropriately in CSV encoder
1 parent7a6ce5f commit805dd49

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+
privatefunctioncleanValueByType($value)
206+
{
207+
if (false ===$value) {
208+
return0;
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+
return1;
219+
}
220+
221+
return$value;
222+
}
223+
197224
privatefunctiongetCsvOptions(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 =newCsvEncoder();
3030
}
3131

32+
publicfunctiontestTrueFalseNullValues()
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
publicfunctiontestSupportEncoding()
3352
{
3453
$this->assertTrue($this->encoder->supportsEncoding('csv'));

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp