Array2XML   A
last analyzed

Complexity

Total Complexity 24

Size/Duplication

Total Lines 164
Duplicated Lines 4.27 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 7
loc 164
rs 10
c 1
b 0
f 0
wmc 24
lcom 1
cbo 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A createXML() 0 8 1
A init() 7 7 1
A bool2str() 0 8 3
C convert() 0 63 15
A getXMLRoot() 0 8 2
A isValidTagName() 0 6 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
 * Array2XML: A class to convert array in PHP to XML
11
 * It also takes into account attributes names unlike SimpleXML in PHP
12
 * It returns the XML in form of DOMDocument class for further manipulation.
13
 * It throws exception if the tag name or attribute name has illegal chars.
14
 *
15
 * Author : Lalit Patel
16
 * Website: http://www.lalit.org/lab/convert-php-array-to-xml-with-attributes
17
 * License: Apache License 2.0
18
 *          http://www.apache.org/licenses/LICENSE-2.0
19
 *
20
 * Usage:
21
 *       $xml = Array2XML::createXML('root_node_name', $php_array);
22
 *       echo $xml->saveXML();
23
 */
24
class Array2XML
25
{
26
    /**
27
     * @var string
28
     */
29
    private static $encoding = 'UTF-8';
30
31
    /**
32
     * @var DomDocument|null
33
     */
34
    private static $xml = null;
35
36
    /**
37
     * Convert an Array to XML.
38
     *
39
     * @param string $node_name - name of the root node to be converted
40
     * @param array  $arr       - array to be converted
41
     *
42
     * @return DomDocument
43
     */
44
    public static function createXML($node_name, $arr = [])
45
    {
46
        $xml = self::getXMLRoot();
47
        $xml->appendChild(self::convert($node_name, $arr));
48
        self::$xml = null;    // clear the xml node in the class for 2nd time use.
49
50
        return $xml;
51
    }
52
53
    /**
54
     * Initialize the root XML node [optional].
55
     *
56
     * @param string $version
57
     * @param string $encoding
58
     * @param bool   $standalone
59
     * @param bool   $format_output
60
     */
61 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...
62
    {
63
        self::$xml = new DomDocument($version, $encoding);
0 ignored issues
show
Documentation Bug introduced by
It seems like new \DOMDocument($version, $encoding) of type object<DOMDocument> is incompatible with the declared type object<LaLit\DomDocument>|null of property $xml.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
64
        self::$xml->xmlStandalone = $standalone;
65
        self::$xml->formatOutput = $format_output;
66
        self::$encoding = $encoding;
67
    }
68
69
    /**
70
     * Get string representation of boolean value.
71
     *
72
     * @param mixed $v
73
     *
74
     * @return string
75
     */
76
    private static function bool2str($v)
77
    {
78
        //convert boolean to text value.
79
        $v = $v === true ? 'true' : $v;
80
        $v = $v === false ? 'false' : $v;
81
82
        return $v;
83
    }
84
85
    /**
86
     * Convert an Array to XML.
87
     *
88
     * @param string $node_name - name of the root node to be converted
89
     * @param array  $arr       - array to be converted
90
     *
91
     * @return DOMNode
92
     *
93
     * @throws Exception
94
     */
95
    private static function convert($node_name, $arr = [])
96
    {
97
        //print_arr($node_name);
98
        $xml = self::getXMLRoot();
99
        $node = $xml->createElement($node_name);
100
101
        if (is_array($arr)) {
102
            // get the attributes first.;
103
            if (array_key_exists('@attributes', $arr) && is_array($arr['@attributes'])) {
104
                foreach ($arr['@attributes'] as $key => $value) {
105
                    if (!self::isValidTagName($key)) {
106
                        throw new Exception('[Array2XML] Illegal character in attribute name. attribute: '.$key.' in node: '.$node_name);
107
                    }
108
                    $node->setAttribute($key, self::bool2str($value));
109
                }
110
                unset($arr['@attributes']); //remove the key from the array once done.
111
            }
112
113
            // check if it has a value stored in @value, if yes store the value and return
114
            // else check if its directly stored as string
115
            if (array_key_exists('@value', $arr)) {
116
                $node->appendChild($xml->createTextNode(self::bool2str($arr['@value'])));
117
                unset($arr['@value']);    //remove the key from the array once done.
118
                //return from recursion, as a note with value cannot have child nodes.
119
                return $node;
120
            } elseif (array_key_exists('@cdata', $arr)) {
121
                $node->appendChild($xml->createCDATASection(self::bool2str($arr['@cdata'])));
122
                unset($arr['@cdata']);    //remove the key from the array once done.
123
                //return from recursion, as a note with cdata cannot have child nodes.
124
                return $node;
125
            }
126
        }
127
128
        //create subnodes using recursion
129
        if (is_array($arr)) {
130
            // recurse to get the node for that key
131
            foreach ($arr as $key => $value) {
132
                if (!self::isValidTagName($key)) {
133
                    throw new Exception('[Array2XML] Illegal character in tag name. tag: '.$key.' in node: '.$node_name);
134
                }
135
                if (is_array($value) && is_numeric(key($value))) {
136
                    // MORE THAN ONE NODE OF ITS KIND;
137
                    // if the new array is numeric index, means it is array of nodes of the same kind
138
                    // it should follow the parent key name
139
                    foreach ($value as $k => $v) {
140
                        $node->appendChild(self::convert($key, $v));
141
                    }
142
                } else {
143
                    // ONLY ONE NODE OF ITS KIND
144
                    $node->appendChild(self::convert($key, $value));
145
                }
146
                unset($arr[$key]); //remove the key from the array once done.
147
            }
148
        }
149
150
        // after we are done with all the keys in the array (if it is one)
151
        // we check if it has any text value, if yes, append it.
152
        if (!is_array($arr)) {
153
            $node->appendChild($xml->createTextNode(self::bool2str($arr)));
154
        }
155
156
        return $node;
157
    }
158
159
    /**
160
     * Get the root XML node, if there isn't one, create it.
161
     *
162
     * @return DomDocument|null
163
     */
164
    private static function getXMLRoot()
165
    {
166
        if (empty(self::$xml)) {
167
            self::init();
168
        }
169
170
        return self::$xml;
171
    }
172
173
    /**
174
     * Check if the tag name or attribute name contains illegal characters
175
     * Ref: http://www.w3.org/TR/xml/#sec-common-syn.
176
     *
177
     * @param string $tag
178
     *
179
     * @return bool
180
     */
181
    private static function isValidTagName($tag)
182
    {
183
        $pattern = '/^[a-z_]+[a-z0-9\:\-\.\_]*[^:]*$/i';
184
185
        return preg_match($pattern, $tag, $matches) && $matches[0] == $tag;
186
    }
187
}
188