diff --git a/src/Symfony/Component/Serializer/CHANGELOG.md b/src/Symfony/Component/Serializer/CHANGELOG.md index 6cd80fdb0b..b78cb659b7 100644 --- a/src/Symfony/Component/Serializer/CHANGELOG.md +++ b/src/Symfony/Component/Serializer/CHANGELOG.md @@ -5,6 +5,7 @@ CHANGELOG ----- * `AbstractNormalizer::handleCircularReference` is now final, and receives two optional extra arguments: the format and the context +* added support for XML comment encoding (encoding `['#comment' => ' foo ']` results ``) 4.1.0 ----- diff --git a/src/Symfony/Component/Serializer/Encoder/XmlEncoder.php b/src/Symfony/Component/Serializer/Encoder/XmlEncoder.php index 0a6cc0edbd..a1ff8c6527 100644 --- a/src/Symfony/Component/Serializer/Encoder/XmlEncoder.php +++ b/src/Symfony/Component/Serializer/Encoder/XmlEncoder.php @@ -22,6 +22,7 @@ use Symfony\Component\Serializer\SerializerAwareTrait; * @author John Wards * @author Fabian Vogler * @author Kévin Dunglas + * @author Dany Maillard */ class XmlEncoder implements EncoderInterface, DecoderInterface, NormalizationAwareInterface, SerializerAwareInterface { @@ -226,6 +227,13 @@ class XmlEncoder implements EncoderInterface, DecoderInterface, NormalizationAwa return false; } + final protected function appendComment(\DOMNode $node, string $data): bool + { + $node->appendChild($this->dom->createComment($data)); + + return true; + } + /** * Checks the name is a valid xml element name. */ @@ -366,6 +374,8 @@ class XmlEncoder implements EncoderInterface, DecoderInterface, NormalizationAwa $parentNode->setAttribute($attributeName, $data); } elseif ('#' === $key) { $append = $this->selectNodeType($parentNode, $data); + } elseif ('#comment' === $key) { + $append = $this->appendComment($parentNode, $data); } elseif (\is_array($data) && false === is_numeric($key)) { // Is this array fully numeric keys? if (ctype_digit(implode('', array_keys($data)))) { diff --git a/src/Symfony/Component/Serializer/Tests/Encoder/XmlEncoderTest.php b/src/Symfony/Component/Serializer/Tests/Encoder/XmlEncoderTest.php index 00e83b5610..fde042928b 100644 --- a/src/Symfony/Component/Serializer/Tests/Encoder/XmlEncoderTest.php +++ b/src/Symfony/Component/Serializer/Tests/Encoder/XmlEncoderTest.php @@ -760,6 +760,19 @@ XML; $this->assertEquals($this->createXmlWithDateTimeField(), $actualXml); } + public function testEncodeComment() + { + $expected = <<<'XML' + + + +XML; + + $data = array('#comment' => ' foo '); + + $this->assertEquals($expected, $this->encoder->encode($data, 'xml')); + } + /** * @return XmlEncoder */