Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 9840d27

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

File tree

2 files changed

+27
-5
lines changed

2 files changed

+27
-5
lines changed

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

Lines changed: 6 additions & 2 deletions
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

Lines changed: 21 additions & 3 deletions
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',
@@ -451,8 +455,22 @@ public function testDecodeNumericNodeValue()
451455

452456
$result = $this->encoder->decode($source, 'xml');
453457
$this->assertEquals($expected, $result);
454-
$this->assertIsInt($result['foo']);
455-
$this->assertIsFloat($result['bar']);
458+
$this->assertInternalType('int', $result['foo']);
459+
$this->assertInternalType('float', $result['bar']);
460+
}
461+
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']);
456474
}
457475

458476
public function testDecodeRootAttributes()

0 commit comments

Comments
 (0)