bug #32007 [Serializer] Handle true and false appropriately in CSV encoder (battye)
This PR was squashed before being merged into the 3.4 branch (closes #32007).
Discussion
----------
[Serializer] Handle true and false appropriately in CSV encoder
| Q | A
| ------------- | ---
| Branch? | 3.4
| Bug fix? | yes
| New feature? | no
| BC breaks? | no
| Deprecations? | no
| Tests pass? | yes
| Fixed tickets | #27642
| License | MIT
| Doc PR | -
Previously, if `true` was passed in as a value to the CSV encoder then `fputcsv()` would correctly treat it as 1. However, if `false` was passed in, it would be treated as a blank value. `null` would also be treated as a blank value.
This fix makes it consistent so that true and false will map to 1 and 0, while null maps to an empty string.
Commits
-------
89cba00c68
[Serializer] Handle true and false appropriately in CSV encoder
This commit is contained in:
commit
b8978bd9ff
@ -189,7 +189,8 @@ class CsvEncoder implements EncoderInterface, DecoderInterface
|
|||||||
if (\is_array($value)) {
|
if (\is_array($value)) {
|
||||||
$this->flatten($value, $result, $keySeparator, $parentKey.$key.$keySeparator);
|
$this->flatten($value, $result, $keySeparator, $parentKey.$key.$keySeparator);
|
||||||
} else {
|
} else {
|
||||||
$result[$parentKey.$key] = $value;
|
// Ensures an actual value is used when dealing with true and false
|
||||||
|
$result[$parentKey.$key] = false === $value ? 0 : (true === $value ? 1 : $value);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -29,6 +29,24 @@ class CsvEncoderTest extends TestCase
|
|||||||
$this->encoder = new CsvEncoder();
|
$this->encoder = new CsvEncoder();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function testTrueFalseValues()
|
||||||
|
{
|
||||||
|
$data = [
|
||||||
|
'string' => 'foo',
|
||||||
|
'int' => 2,
|
||||||
|
'false' => false,
|
||||||
|
'true' => true,
|
||||||
|
];
|
||||||
|
|
||||||
|
// Check that true and false are appropriately handled
|
||||||
|
$this->assertEquals(<<<'CSV'
|
||||||
|
string,int,false,true
|
||||||
|
foo,2,0,1
|
||||||
|
|
||||||
|
CSV
|
||||||
|
, $this->encoder->encode($data, 'csv'));
|
||||||
|
}
|
||||||
|
|
||||||
public function testSupportEncoding()
|
public function testSupportEncoding()
|
||||||
{
|
{
|
||||||
$this->assertTrue($this->encoder->supportsEncoding('csv'));
|
$this->assertTrue($this->encoder->supportsEncoding('csv'));
|
||||||
|
Reference in New Issue
Block a user