Completed
Push — master ( 5f0ee2...6f3a7a )
by Lorenzo
04:41
created

xml.php ➔ xml2array()   D

Complexity

Conditions 31
Paths 100

Size

Total Lines 110
Code Lines 85

Duplication

Lines 8
Ratio 7.27 %

Importance

Changes 0
Metric Value
cc 31
eloc 85
c 0
b 0
f 0
nc 100
nop 3
dl 8
loc 110
rs 4.3983

How to fix   Long Method    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
/**
4
 * Fetch URL with fopen() && returns a well formed array like the structure of the xml-document.
5
 * If somethins goes wrong return an empty array.
6
 * @param string $url
7
 * @param int $get_attributes
8
 * @param string $priority
9
 * @return array
10
 */
11
function xmlUrl2array(string $url, int $get_attributes = 1, string $priority = 'tag') : array
12
{
13
    $contents = "";
14
    if (!function_exists('xml_parser_create')) {
15
        return array();
16
    }
17
    if (!($fp = @ fopen($url, 'rb'))) {
18
        return array();
19
    }
20
    while (!feof($fp)) {
21
        $contents .= fread($fp, 8192);
22
    }
23
    fclose($fp);
24
25
    if (!$contents) {
26
        return array();
27
    }
28
29
    return xmlUrl2array($contents, $get_attributes, $priority);
30
}
31
32
/**
33
 * Returns a well formed array like the structure of the xml-document
34
 * If somethins goes wrong return an empty array.
35
 * @param string $xml
36
 * @param int $get_attributes
37
 * @param string $priority
38
 * @return array
39
 */
40
function xml2array(string $xml, int $get_attributes = 1, string $priority = 'tag') : array
41
{
42
    if (!function_exists('xml_parser_create')) {
43
        return array();
44
    }
45
    if (!$xml) {
46
        return array();
47
    }
48
    $contents = $xml;
49
    $parser = xml_parser_create('');
50
    xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
51
    xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
52
    xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
53
    xml_parse_into_struct($parser, trim($contents), $xml_values);
54
    xml_parser_free($parser);
55
    if (!$xml_values) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $xml_values of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
56
        return array();
57
    } //Hmm...
58
    $xml_array = array();
59
    $parents = array();
0 ignored issues
show
Unused Code introduced by
$parents is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
60
    $opened_tags = array();
0 ignored issues
show
Unused Code introduced by
$opened_tags is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
61
    $arr = array();
0 ignored issues
show
Unused Code introduced by
$arr is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
62
    $current = &$xml_array;
63
    $repeated_tag_index = array();
64
    foreach ($xml_values as $data) {
65
        unset ($attributes, $value);
66
        extract($data);
67
        $result = array();
68
        $attributes_data = array();
69
        if (isset ($value)) {
70
            if ($priority == 'tag') {
71
                $result = $value;
72
            } else {
73
                $result['value'] = $value;
74
            }
75
        }
76
        if (isset ($attributes) && $get_attributes) {
77
            foreach ($attributes as $attr => $val) {
78
                if ($priority == 'tag') {
79
                    $attributes_data[$attr] = $val;
80
                } else {
81
                    $result['attr'][$attr] = $val;
82
                } //Set all the attributes in a array called 'attr'
83
            }
84
        }
85
        if ($type == "open") {
86
            $parent[$level - 1] = &$current;
87
            if (!is_array($current) or (!in_array($tag, array_keys($current)))) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
88
                $current[$tag] = $result;
89
                if ($attributes_data) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $attributes_data of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
90
                    $current[$tag . '_attr'] = $attributes_data;
91
                }
92
                $repeated_tag_index[$tag . '_' . $level] = 1;
93
                $current = &$current[$tag];
94
            } else {
95
                if (isset ($current[$tag][0])) {
96
                    $current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
97
                    $repeated_tag_index[$tag . '_' . $level]++;
98
                } else {
99
                    $current[$tag] = array(
100
                        $current[$tag],
101
                        $result
102
                    );
103
                    $repeated_tag_index[$tag . '_' . $level] = 2;
104 View Code Duplication
                    if (isset ($current[$tag . '_attr'])) {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across 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...
105
                        $current[$tag]['0_attr'] = $current[$tag . '_attr'];
106
                        unset ($current[$tag . '_attr']);
107
                    }
108
                }
109
                $last_item_index = $repeated_tag_index[$tag . '_' . $level] - 1;
110
                $current = &$current[$tag][$last_item_index];
111
            }
112
        } elseif ($type == "complete") {
113
            if (!isset ($current[$tag])) {
114
                $current[$tag] = $result;
115
                $repeated_tag_index[$tag . '_' . $level] = 1;
116
                if ($priority == 'tag' && $attributes_data) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $attributes_data of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
117
                    $current[$tag . '_attr'] = $attributes_data;
118
                }
119
            } else {
120
                if (is_array($current[$tag]) && isset ($current[$tag][0])) {
121
                    $current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
122
                    if ($priority == 'tag' && $get_attributes && $attributes_data) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $attributes_data of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
123
                        $current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
124
                    }
125
                    $repeated_tag_index[$tag . '_' . $level]++;
126
                } else {
127
                    $current[$tag] = array(
128
                        $current[$tag],
129
                        $result
130
                    );
131
                    $repeated_tag_index[$tag . '_' . $level] = 1;
132
                    if ($priority == 'tag' && $get_attributes) {
133 View Code Duplication
                        if (isset ($current[$tag . '_attr'])) {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across 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...
134
                            $current[$tag]['0_attr'] = $current[$tag . '_attr'];
135
                            unset ($current[$tag . '_attr']);
136
                        }
137
                        if ($attributes_data) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $attributes_data of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
138
                            $current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
139
                        }
140
                    }
141
                    $repeated_tag_index[$tag . '_' . $level]++; //0 && 1 index is already taken
142
                }
143
            }
144
        } elseif ($type == 'close') {
145
            $current = &$parent[$level - 1];
146
        }
147
    }
148
    return $xml_array;
149
}
150
151
/**
152
 * @param array $arrData
153
 * @param string $rootXml
154
 * @return string
155
 */
156
function array2xml(array $arrData, string $rootXml = '<root></root>') : string
157
{
158
    // creating object of SimpleXMLElement
159
    $objXml = new SimpleXMLElement('<?xml version="1.0"?>' . ($rootXml ? $rootXml : '<root></root>'));
160
    array2SimpleXMLElement($arrData, $objXml);
161
    return trim($objXml->asXML());
162
}
163
164
/**
165
 * @param array $arrData
166
 * @param SimpleXMLElement $objXml
167
 */
168
function array2SimpleXMLElement(array $arrData, SimpleXMLElement $objXml)
169
{
170
    foreach ($arrData as $key => $value) {
171
        if (is_array($value)) {
172
            if (!is_numeric($key)) {
173
                $subnode = $objXml->addChild("$key");
174
                array2SimpleXMLElement($value, $subnode);
175
            } else {
176
                array2SimpleXMLElement($value, $objXml);
177
            }
178
        } else {
179
            $objXml->addChild("$key", "$value");
180
        }
181
    }
182
}
183