diff --git a/src/XmlToArray.php b/src/XmlToArray.php index b0ccba5..29371b2 100755 --- a/src/XmlToArray.php +++ b/src/XmlToArray.php @@ -44,50 +44,45 @@ protected function convertAttributes(DOMNamedNodeMap $nodeMap): ?array return ['_attributes' => $result]; } - protected function isHomogenous(array $arr) - { - $firstValue = current($arr); - foreach ($arr as $val) { - if ($firstValue !== $val) { - return false; - } - } - - return true; - } - protected function convertDomElement(DOMElement $element) { - $sameNames = false; $result = $this->convertAttributes($element->attributes); + $sameNamesOccurrences = []; + if ($element->childNodes->length > 1) { $childNodeNames = []; - foreach ($element->childNodes as $key => $node) { + + foreach ($element->childNodes as $node) { $childNodeNames[] = $node->nodeName; } - $sameNames = $this->isHomogenous($childNodeNames); + + $sameNamesOccurrences = array_count_values($childNodeNames); } - foreach ($element->childNodes as $key => $node) { + foreach ($element->childNodes as $node) { if ($node instanceof DOMCdataSection) { $result['_cdata'] = $node->data; continue; } + if ($node instanceof DOMText) { $result = $node->textContent; continue; } + if ($node instanceof DOMElement) { - if ($sameNames) { - $result[$node->nodeName][$key] = $this->convertDomElement($node); - } else { - $result[$node->nodeName] = $this->convertDomElement($node); + $nodeName = $node->nodeName; + $hasSameName = array_key_exists($nodeName, $sameNamesOccurrences) && $sameNamesOccurrences[$nodeName] > 1; + + if ($hasSameName === false) { + $result[$nodeName] = $this->convertDomElement($node); + continue; } - continue; + $result[$nodeName][] = $this->convertDomElement($node); } } diff --git a/tests/XmlToArrayTest.php b/tests/XmlToArrayTest.php index 20b81c5..fc17043 100755 --- a/tests/XmlToArrayTest.php +++ b/tests/XmlToArrayTest.php @@ -71,7 +71,6 @@ public function data() public function sameNameTest(array $array) { $xml = ArrayToXml::convert($array, 'items'); - $convertedArr = XmlToArray::convert($xml); $this->assertSame(['items' => $array], XmlToArray::convert($xml)); } @@ -83,16 +82,30 @@ public function sameNameData() 'Facilities' => [ 'Facility' => [ [ - '_attributes' => ['Code'=>'*EC'], - '_cdata' => 'Earliest check-in at 14:00', + '_attributes' => ['Code' => '*EC'], + '_cdata' => 'Earliest check-in at 14:00', ], [ - '_attributes' => ['Code'=>'*LF'], - '_cdata' => '1 lift', + '_attributes' => ['Code' => '*LF'], + '_cdata' => '1 lift', ], [ - '_attributes' => ['Code'=>'*RS'], - '_cdata' => 'Room Service from 18:00 to 21:00', + '_attributes' => ['Code' => '*RS'], + '_cdata' => 'Room Service from 18:00 to 21:00', + ], + ], + 'Locations' => [ + [ + '_attributes' => ['ShortCode' => 'GB'], + '_cdata' => 'United Kingdom', + ], + [ + '_attributes' => ['ShortCode' => 'USA'], + '_cdata' => 'United States of America', + ], + [ + '_attributes' => ['ShortCode' => 'AMS'], + '_cdata' => 'Amsterdam', ], ], ],