feature #25369 [Serializer] add a context key to return always as collection for XmlEncoder (Simperfit)

This PR was merged into the 4.1-dev branch.

Discussion
----------

[Serializer] add a context key to return always as collection for XmlEncoder

| Q             | A
| ------------- | ---
| Branch?       | 4.1
| Bug fix?      | no
| New feature?  | yes
| BC breaks?    | no
| Deprecations? | no <!-- don't forget to update UPGRADE-*.md files -->
| Tests pass?   | yes
| Fixed tickets | #25227
| License       | MIT
| Doc PR        |

This PR add a new `as_collection` context key in order to return always as a collection instead of returning a single elements when there are only one array.

there are only one PR for the CsvEncoder don't wanted to have only One PR containing the two changes. It feel better to have two PR that fix the behaviour on two different things. it's easy to review and to revert if it break something (which should not since we are testing the behaviour).

Commits
-------

adb428d314 [Serializer] add a context key to return always as collection for XmlEncoder
This commit is contained in:
Kévin Dunglas 2018-02-19 14:49:10 +01:00
commit 81e19e8392
No known key found for this signature in database
GPG Key ID: 4D04EBEF06AAF3A6
2 changed files with 28 additions and 1 deletions

View File

@ -335,7 +335,7 @@ class XmlEncoder implements EncoderInterface, DecoderInterface, NormalizationAwa
}
foreach ($value as $key => $val) {
if (\is_array($val) && 1 === \count($val)) {
if (empty($context['as_collection']) && \is_array($val) && 1 === \count($val)) {
$value[$key] = current($val);
}
}

View File

@ -515,6 +515,33 @@ XML;
$this->assertEquals($expected, $this->encoder->decode($source, 'xml'));
}
public function testDecodeAlwaysAsCollection()
{
$this->encoder = new XmlEncoder('response', null);
$serializer = new Serializer(array(new CustomNormalizer()), array('xml' => new XmlEncoder()));
$this->encoder->setSerializer($serializer);
$source = <<<'XML'
<?xml version="1.0"?>
<order_rows nodeType="order_row" virtualEntity="true">
<order_row>
<id><![CDATA[16]]></id>
<test><![CDATA[16]]></test>
</order_row>
</order_rows>
XML;
$expected = array(
'@nodeType' => 'order_row',
'@virtualEntity' => 'true',
'order_row' => array(array(
'id' => array(16),
'test' => array(16),
)),
);
$this->assertEquals($expected, $this->encoder->decode($source, 'xml', array('as_collection' => true)));
}
public function testDecodeWithoutItemHash()
{
$obj = new ScalarDummy();