Skip to content

Commit 967f070

Browse files
committed
Support cast to null when node is empty
1 parent 63de18f commit 967f070

File tree

2 files changed

+25
-3
lines changed

2 files changed

+25
-3
lines changed

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

+6-2
Original file line numberDiff line numberDiff line change
@@ -323,12 +323,16 @@ private function parseXmlAttributes(\DOMNode $node, array $context = []): array
323323
*/
324324
private function parseXmlValue(\DOMNode $node, array $context = [])
325325
{
326+
$typeCastNodes = (bool) ($context[self::TYPE_CAST_NODES] ?? $this->defaultContext[self::TYPE_CAST_NODES]);
327+
326328
if (!$node->hasChildNodes()) {
329+
if ($typeCastNodes && '' === $node->nodeValue) {
330+
return null;
331+
}
332+
327333
return $node->nodeValue;
328334
}
329335

330-
$typeCastNodes = (bool) ($context[self::TYPE_CAST_NODES] ?? $this->defaultContext[self::TYPE_CAST_NODES]);
331-
332336
if (1 === $node->childNodes->length && \in_array($node->firstChild->nodeType, [XML_TEXT_NODE, XML_CDATA_SECTION_NODE])) {
333337
if (!is_numeric($node->firstChild->nodeValue) || !$typeCastNodes) {
334338
return $node->firstChild->nodeValue;

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

+19-1
Original file line numberDiff line numberDiff line change
@@ -301,7 +301,11 @@ public function testNoTypeCastAttribute()
301301
</document>
302302
XML;
303303

304-
$data = $this->encoder->decode($source, 'xml', ['xml_type_cast_attributes' => false]);
304+
$data = $this->encoder->decode($source, 'xml', [
305+
XmlEncoder::TYPE_CAST_ATTRIBUTES => false,
306+
XmlEncoder::TYPE_CAST_NODES => false,
307+
]);
308+
305309
$expected = [
306310
'@a' => '018',
307311
'@b' => '-12.11',
@@ -455,6 +459,20 @@ public function testDecodeNumericNodeValue()
455459
$this->assertIsFloat($result['bar']);
456460
}
457461

462+
public function testDecodeEmptyNodeValue()
463+
{
464+
$source = '<?xml version="1.0"?>'."\n".
465+
'<response><foo/></response>'."\n";
466+
467+
$expected = [
468+
'foo' => null,
469+
];
470+
471+
$result = $this->encoder->decode($source, 'xml');
472+
$this->assertEquals($expected, $result);
473+
$this->assertNull($result['foo']);
474+
}
475+
458476
public function testDecodeRootAttributes()
459477
{
460478
$source = '<?xml version="1.0"?>'."\n".

0 commit comments

Comments
 (0)