Passed
Push — master ( 3896ee...e50616 )
by Raffael
05:45
created

Converter::xmlToArray()   B

Complexity

Conditions 11
Paths 10

Size

Total Lines 40

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 11.307

Importance

Changes 0
Metric Value
dl 0
loc 40
ccs 19
cts 22
cp 0.8636
rs 7.3166
c 0
b 0
f 0
cc 11
nc 10
nop 1
crap 11.307

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 2
    public static function xmlToArray($root)
20
    {
21 2
        $result = [];
22
23 2
        if ($root->hasAttributes()) {
24 1
            $attrs = $root->attributes;
25 1
            foreach ($attrs as $attr) {
26 1
                $result['@attributes'][$attr->name] = $attr->value;
27
            }
28
        }
29
30 2
        if ($root->hasChildNodes()) {
31 2
            $children = $root->childNodes;
32
33 2
            if ($children->length == 1) {
34 2
                $child = $children->item(0);
35
36 2
                if ($child->nodeType === XML_TEXT_NODE || $child->nodeType === XML_CDATA_SECTION_NODE) {
37 2
                    $result['_value'] = $child->nodeValue;
38
39 2
                    return count($result) == 1 ? $result['_value'] : $result;
40
                }
41
            }
42
43 2
            $groups = [];
44 2
            foreach ($children as $child) {
45 2
                if (!isset($result[$child->nodeName])) {
46 2
                    $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 2
                    $result[$child->nodeName][] = self::xmlToArray($child);
53
                }
54
            }
55
        }
56
57 2
        return $result;
58
    }
59
}
60