Skip to content

Commit

Permalink
bug #17984 Allow to normalize \Traversable when serializing xml (Ener…
Browse files Browse the repository at this point in the history
…-Getick)

This PR was merged into the 2.3 branch.

Discussion
----------

Allow to normalize \Traversable when serializing xml

| Q             | A
| ------------- | ---
| Bug fix?      | yes
| New feature?  | no
| BC breaks?    | no
| Deprecations? | no
| Tests pass?   | no
| Fixed tickets |
| License       | MIT

It's impossible to normalize an object implementing ``\Traversable`` when using the ``XMLEncoder``. For example we can't customize the serializer output when serializing a ``FormInterface`` instance.

So my proposition is to fix this by using the default XML encoder output only when the serializer can't normalize the data.

Commits
-------

97c5d27 Allow to normalize \Traversable
  • Loading branch information
fabpot committed Mar 4, 2016
2 parents 8713c7e + 97c5d27 commit 9a5ea71
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/Symfony/Component/Serializer/Encoder/XmlEncoder.php
Expand Up @@ -305,7 +305,7 @@ private function buildXml(\DOMElement $parentNode, $data, $xmlRootNodeName = nul
{
$append = true;

if (is_array($data) || $data instanceof \Traversable) {
if (is_array($data) || ($data instanceof \Traversable && !$this->serializer->supportsNormalization($data, $this->format))) {
foreach ($data as $key => $data) {
//Ah this is the magic @ attribute types.
if (0 === strpos($key, '@') && is_scalar($data) && $this->isElementNameValid($attributeName = substr($key, 1))) {
Expand Down
16 changes: 16 additions & 0 deletions src/Symfony/Component/Serializer/Tests/Encoder/XmlEncoderTest.php
Expand Up @@ -12,6 +12,7 @@
namespace Symfony\Component\Serializer\Tests\Encoder;

use Symfony\Component\Serializer\Tests\Fixtures\Dummy;
use Symfony\Component\Serializer\Tests\Fixtures\NormalizableTraversableDummy;
use Symfony\Component\Serializer\Tests\Fixtures\ScalarDummy;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Serializer;
Expand Down Expand Up @@ -203,6 +204,21 @@ public function testEncodeSerializerXmlRootNodeNameOption()
$this->assertEquals($expected, $serializer->serialize($array, 'xml', $options));
}

public function testEncodeTraversableWhenNormalizable() {
$this->encoder = new XmlEncoder();
$serializer = new Serializer(array(new CustomNormalizer()), array('xml' => new XmlEncoder()));
$this->encoder->setSerializer($serializer);

$expected = <<<XML
<?xml version="1.0"?>
<response><foo>normalizedFoo</foo><bar>normalizedBar</bar></response>
XML;

$this->assertEquals($expected, $serializer->serialize(new NormalizableTraversableDummy(), 'xml'));

}

public function testDecode()
{
$source = $this->getXmlSource();
Expand Down

0 comments on commit 9a5ea71

Please sign in to comment.