Completed
Push — master ( 316baf...2178d1 )
by Raffael
67:25 queued 62:39
created

Converter::xmlToArray()   B

Complexity

Conditions 11
Paths 10

Size

Total Lines 40

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 132

Importance

Changes 0
Metric Value
dl 0
loc 40
ccs 0
cts 33
cp 0
rs 7.3166
c 0
b 0
f 0
cc 11
nc 10
nop 1
crap 132

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
/**
6
 * tubee.io
7
 *
8
 * @copyright   Copryright (c) 2017-2019 gyselroth GmbH (https://gyselroth.com)
9
 * @license     GPL-3.0 https://opensource.org/licenses/GPL-3.0
10
 */
11
12
namespace Tubee\Endpoint\Xml;
13
14
class Converter
15
{
16
    /**
17
     * Convert XMLElement into nicly formatted php array.
18
     */
19
    public static function xmlToArray($root)
20
    {
21
        $result = [];
22
23
        if ($root->hasAttributes()) {
24
            $attrs = $root->attributes;
25
            foreach ($attrs as $attr) {
26
                $result['@attributes'][$attr->name] = $attr->value;
27
            }
28
        }
29
30
        if ($root->hasChildNodes()) {
31
            $children = $root->childNodes;
32
33
            if ($children->length == 1) {
34
                $child = $children->item(0);
35
36
                if ($child->nodeType === XML_TEXT_NODE || $child->nodeType === XML_CDATA_SECTION_NODE) {
37
                    $result['_value'] = $child->nodeValue;
38
39
                    return count($result) == 1 ? $result['_value'] : $result;
40
                }
41
            }
42
43
            $groups = [];
44
            foreach ($children as $child) {
45
                if (!isset($result[$child->nodeName])) {
46
                    $result[$child->nodeName] = self::xmlToArray($child);
47
                } else {
48
                    if (!isset($groups[$child->nodeName])) {
49
                        $result[$child->nodeName] = [$result[$child->nodeName]];
50
                        $groups[$child->nodeName] = 1;
51
                    }
52
                    $result[$child->nodeName][] = self::xmlToArray($child);
53
                }
54
            }
55
        }
56
57
        return $result;
58
    }
59
}
60