Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/Symfony/Component/Serializer/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<!-- foo -->`)

4.1.0
-----
Expand Down
10 changes: 10 additions & 0 deletions src/Symfony/Component/Serializer/Encoder/XmlEncoder.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
* @author John Wards <jwards@whiteoctober.co.uk>
* @author Fabian Vogler <fabian@equivalence.ch>
* @author Kévin Dunglas <dunglas@gmail.com>
* @author Dany Maillard <danymaillard93b@gmail.com>
*/
class XmlEncoder implements EncoderInterface, DecoderInterface, NormalizationAwareInterface, SerializerAwareInterface
{
Expand Down Expand Up @@ -226,6 +227,13 @@ final protected function appendDocumentFragment(\DOMNode $node, $fragment): bool
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.
*/
Expand Down Expand Up @@ -366,6 +374,8 @@ private function buildXml(\DOMNode $parentNode, $data, string $xmlRootNodeName =
$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)))) {
Expand Down
13 changes: 13 additions & 0 deletions src/Symfony/Component/Serializer/Tests/Encoder/XmlEncoderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -760,6 +760,19 @@ public function testEncodeXmlWithDateTimeObjectField()
$this->assertEquals($this->createXmlWithDateTimeField(), $actualXml);
}

public function testEncodeComment()
{
$expected = <<<'XML'
<?xml version="1.0"?>
<response><!-- foo --></response>

XML;

$data = array('#comment' => ' foo ');

$this->assertEquals($expected, $this->encoder->encode($data, 'xml'));
}

/**
* @return XmlEncoder
*/
Expand Down