XML2Array   A
last analyzed

Complexity

Total Complexity 26

Size/Duplication

Total Lines 149
Duplicated Lines 4.7 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 4
Bugs 1 Features 0
Metric Value
dl 7
loc 149
rs 10
c 4
b 1
f 0
wmc 26
lcom 1
cbo 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
C createArray() 0 24 7
A init() 7 7 1
C convert() 0 65 16
A getXMLRoot() 0 8 2

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
namespace LaLit;
4
5
use DOMDocument;
6
use DOMNode;
7
use Exception;
8
9
/**
10
 * XML2Array: A class to convert XML to array in PHP
11
 * It returns the array which can be converted back to XML using the Array2XML script
12
 * It takes an XML string or a DOMDocument object as an input.
13
 *
14
 * See Array2XML: http://www.lalit.org/lab/convert-php-array-to-xml-with-attributes
15
 *
16
 * Author : Lalit Patel
17
 * Website: http://www.lalit.org/lab/convert-xml-to-array-in-php-xml2array
18
 * License: Apache License 2.0
19
 *          http://www.apache.org/licenses/LICENSE-2.0
20
 *
21
 * Usage:
22
 *       $array = XML2Array::createArray($xml);
23
 */
24
class XML2Array
25
{
26
    /**
27
     * @var string
28
     */
29
    private static $encoding = 'UTF-8';
30
31
    /**
32
     * @var DOMDocument
33
     */
34
    private static $xml = null;
35
36
    /**
37
     * Convert an XML to Array.
38
     *
39
     * @param string|DOMDocument $input_xml
40
     *
41
     * @return array
42
     *
43
     * @throws Exception
44
     */
45
    public static function createArray($input_xml)
46
    {
47
        $xml = self::getXMLRoot();
48
        if (is_string($input_xml)) {
49
            try {
50
                $xml->loadXML($input_xml);
51
                if (!is_object($xml) || empty($xml->documentElement)) {
52
                    throw new Exception();
53
                }
54
            } catch (Exception $ex) {
55
                throw new Exception('[XML2Array] Error parsing the XML string.'.PHP_EOL.$ex->getMessage());
56
            }
57
        } elseif (is_object($input_xml)) {
58
            if (get_class($input_xml) != 'DOMDocument') {
59
                throw new Exception('[XML2Array] The input XML object should be of type: DOMDocument.');
60
            }
61
            $xml = self::$xml = $input_xml;
62
        } else {
63
            throw new Exception('[XML2Array] Invalid input');
64
        }
65
        $array[$xml->documentElement->tagName] = self::convert($xml->documentElement);
0 ignored issues
show
Coding Style Comprehensibility introduced by
$array was never initialized. Although not strictly required by PHP, it is generally a good practice to add $array = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
66
        self::$xml = null;    // clear the xml node in the class for 2nd time use.
67
        return $array;
68
    }
69
70
    /**
71
     * Initialize the root XML node [optional].
72
     *
73
     * @param string $version
74
     * @param string $encoding
75
     * @param bool   $standalone
76
     * @param bool   $format_output
77
     */
78 View Code Duplication
    public static function init($version = '1.0', $encoding = 'utf-8', $standalone = false, $format_output = true)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
79
    {
80
        self::$xml = new DomDocument($version, $encoding);
81
        self::$xml->xmlStandalone = $standalone;
82
        self::$xml->formatOutput = $format_output;
83
        self::$encoding = $encoding;
84
    }
85
86
    /**
87
     * Convert an Array to XML.
88
     *
89
     * @param DOMNode $node - XML as a string or as an object of DOMDocument
90
     *
91
     * @return array
92
     */
93
    private static function convert(DOMNode $node)
94
    {
95
        $output = [];
96
97
        switch ($node->nodeType) {
98
            case XML_CDATA_SECTION_NODE:
99
                $output['@cdata'] = trim($node->textContent);
100
                break;
101
102
            case XML_TEXT_NODE:
103
                $output = trim($node->textContent);
104
                break;
105
106
            case XML_ELEMENT_NODE:
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
107
108
                // for each child node, call the covert function recursively
109
                for ($i = 0, $m = $node->childNodes->length; $i < $m; ++$i) {
110
                    $child = $node->childNodes->item($i);
111
                    $v = self::convert($child);
112
                    if (isset($child->tagName)) {
113
                        $t = $child->tagName;
114
115
                        // assume more nodes of same kind are coming
116
                        if (!array_key_exists($t, $output)) {
117
                            $output[$t] = [];
118
                        }
119
                        $output[$t][] = $v;
120
                    } else {
121
                        //check if it is not an empty node
122
                        if (!empty($v)) {
123
                            $output = $v;
124
                        }
125
                    }
126
                }
127
128
                if (is_array($output)) {
129
                    // if only one node of its kind, assign it directly instead if array($value);
130
                    foreach ($output as $t => $v) {
131
                        if (is_array($v) && count($v) == 1) {
132
                            $output[$t] = $v[0];
133
                        }
134
                    }
135
                    if (empty($output)) {
136
                        //for empty nodes
137
                        $output = '';
138
                    }
139
                }
140
141
                // loop through the attributes and collect them
142
                if ($node->attributes->length) {
0 ignored issues
show
Bug introduced by
The property length does not seem to exist in DOMNamedNodeMap.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
143
                    $a = [];
144
                    foreach ($node->attributes as $attrName => $attrNode) {
145
                        $a[$attrName] = $attrNode->value;
146
                    }
147
                    // if its an leaf node, store the value in @value instead of directly storing it.
148
                    if (!is_array($output)) {
149
                        $output = ['@value' => $output];
150
                    }
151
                    $output['@attributes'] = $a;
152
                }
153
                break;
154
        }
155
156
        return $output;
157
    }
158
159
    /**
160
     * Get the root XML node, if there isn't one, create it.
161
     *
162
     * @return DOMDocument
163
     */
164
    private static function getXMLRoot()
165
    {
166
        if (empty(self::$xml)) {
167
            self::init();
168
        }
169
170
        return self::$xml;
171
    }
172
}
173