Skip to content

Commit b19ce4e

Browse files
author
Amrouche Hamza
committed
[Serializer] add a context key to return csv always as collection
1 parent 424cbcc commit b19ce4e

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

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

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,13 +32,15 @@ class CsvEncoder implements EncoderInterface, DecoderInterface
3232
private $enclosure;
3333
private $escapeChar;
3434
private $keySeparator;
35+
private $forceCollection;
3536

36-
public function __construct(string $delimiter = ',', string $enclosure = '"', string $escapeChar = '\\', string $keySeparator = '.')
37+
public function __construct(string $delimiter = ',', string $enclosure = '"', string $escapeChar = '\\', string $keySeparator = '.', bool $forceCollection = false)
3738
{
3839
$this->delimiter = $delimiter;
3940
$this->enclosure = $enclosure;
4041
$this->escapeChar = $escapeChar;
4142
$this->keySeparator = $keySeparator;
43+
$this->forceCollection = $forceCollection;
4244
}
4345

4446
/**
@@ -150,6 +152,10 @@ public function decode($data, $format, array $context = array())
150152
}
151153
fclose($handle);
152154

155+
if ($this->forceCollection) {
156+
return $result;
157+
}
158+
153159
if (empty($result) || isset($result[1])) {
154160
return $result;
155161
}

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

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -208,6 +208,22 @@ public function testDecodeCollection()
208208
, 'csv'));
209209
}
210210

211+
public function testDecodeOnlyOneAsCollection()
212+
{
213+
$this->encoder = new CsvEncoder(',', '"', '\\', '.', true);
214+
215+
$expected = array(
216+
array('foo' => 'a'),
217+
);
218+
219+
$this->assertEquals($expected, $this->encoder->decode(<<<'CSV'
220+
foo
221+
a
222+
223+
CSV
224+
, 'csv'));
225+
}
226+
211227
public function testDecodeToManyRelation()
212228
{
213229
$expected = array(

0 commit comments

Comments
 (0)