Completed
Push — master ( de530c...b7d7e5 )
by Greg
02:22
created

DomToArraySimplifier::getUniformChildren()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
c 1
b 1
f 0
dl 0
loc 12
rs 9.4285
cc 3
eloc 8
nc 3
nop 2
1
<?php
2
namespace Consolidation\OutputFormatters\Transformations;
3
4
use Consolidation\OutputFormatters\SimplifyToArrayInterface;
5
use Consolidation\OutputFormatters\FormatterOptions;
6
use Consolidation\OutputFormatters\StructuredData\Xml\DomDataInterface;
7
use Consolidation\OutputFormatters\StructuredData\Xml\XmlSchema;
8
9
/**
10
 * Simplify a DOMDocument to an array.
11
 */
12
class DomToArraySimplifier implements SimplifyToArrayInterface
13
{
14
    public function __construct()
15
    {
16
    }
17
18
    public function simplifyToArray($structuredData, FormatterOptions $options)
19
    {
20
        if ($structuredData instanceof DomDataInterface) {
21
            $structuredData = $structuredData->getDomData();
22
        }
23
        if ($structuredData instanceof \DOMDocument) {
24
            // $schema = $options->getXmlSchema();
0 ignored issues
show
Unused Code Comprehensibility introduced by
55% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
25
            $simplified = $this->elementToArray($structuredData);
26
            $structuredData = array_shift($simplified);
27
        }
28
        return $structuredData;
29
    }
30
31
    /**
32
     * Recursively convert the provided DOM element into a php array.
33
     *
34
     * @param \DOMNode $element
35
     * @return type
36
     */
37
    protected function elementToArray(\DOMNode $element)
38
    {
39
        if ($element->nodeType == XML_TEXT_NODE) {
40
            return $element->nodeValue;
41
        }
42
        $attributes = $this->getNodeAttributes($element);
0 ignored issues
show
Documentation introduced by
$element is of type object<DOMNode>, but the function expects a object<Consolidation\Out...s\Transformations\type>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
43
        $children = $this->getNodeChildren($element);
0 ignored issues
show
Documentation introduced by
$element is of type object<DOMNode>, but the function expects a object<Consolidation\Out...s\Transformations\type>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
44
45
        return array_merge($attributes, $children);
46
    }
47
48
    /**
49
     * Get all of the attributes of the provided element.
50
     *
51
     * @param type $element
52
     * @return type
53
     */
54
    protected function getNodeAttributes($element)
55
    {
56
        if (empty($element->attributes)) {
57
            return [];
58
        }
59
        $attributes = [];
60
        foreach ($element->attributes as $key => $attribute) {
61
            $attributes[$key] = $attribute->nodeValue;
62
        }
63
        return $attributes;
64
    }
65
66
    /**
67
     * Get all of the children of the provided element, with simplification.
68
     *
69
     * @param type $element
70
     * @return type
71
     */
72
    protected function getNodeChildren($element)
73
    {
74
        if (empty($element->childNodes)) {
75
            return [];
76
        }
77
        $uniformChildrenName = $this->hasUniformChildren($element);
78
        if ("{$uniformChildrenName}s" == $element->nodeName) {
79
            $result = $this->getUniformChildren($element->nodeName, $element);
80
        } else {
81
            $result = $this->getUniqueChildren($element->nodeName, $element);
82
        }
83
        return $result;
84
    }
85
86
    /**
87
     * Get the data from the children of the provided node in preliminary
88
     * form.
89
     *
90
     * @param type $element
91
     * @return type
92
     */
93
    protected function getNodeChildrenData($element)
94
    {
95
        $children = [];
96
        foreach ($element->childNodes as $key => $value) {
97
            $children[$key] = $this->elementToArray($value);
98
        }
99
        return $children;
100
    }
101
102
    /**
103
     * Determine whether the children of the provided element are uniform.
104
     * @see getUniformChildren(), below.
105
     *
106
     * @param type $element
107
     * @return type
108
     */
109
    protected function hasUniformChildren($element)
110
    {
111
        $last = false;
112
        foreach ($element->childNodes as $key => $value) {
113
            $name = $value->nodeName;
114
            if (!$name) {
115
                return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by Consolidation\OutputForm...ier::hasUniformChildren of type Consolidation\OutputForm...rs\Transformations\type.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
116
            }
117
            if ($last && ($name != $last)) {
118
                return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by Consolidation\OutputForm...ier::hasUniformChildren of type Consolidation\OutputForm...rs\Transformations\type.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
119
            }
120
            $last = $name;
121
        }
122
        return $last;
123
    }
124
125
    /**
126
     * Convert the children of the provided DOM element into an array.
127
     * Here, 'uniform' means that all of the element names of the children
128
     * are identical, and further, the element name of the parent is the
129
     * plural form of the child names.  When the children are uniform in
130
     * this way, then the parent element name will be used as the key to
131
     * store the children in, and the child list will be returned as a
132
     * simple list with their (duplicate) element names omitted.
133
     *
134
     * @param type $parentKey
135
     * @param type $element
136
     * @return type
137
     */
138
    protected function getUniformChildren($parentKey, $element)
139
    {
140
        $children = $this->getNodeChildrenData($element);
141
        $simplifiedChildren = [];
142
        foreach ($children as $key => $value) {
143
            if ($this->valueCanBeSimplified($value)) {
144
                $value = array_shift($value);
145
            }
146
            $simplifiedChildren[$parentKey][] = $value;
147
        }
148
        return $simplifiedChildren;
149
    }
150
151
    /**
152
     * Determine whether the provided value has additional unnecessary
153
     * nesting.  {"color": "red"} is converted to "red". No other
154
     * simplification is done.
155
     *
156
     * @param type $value
157
     * @return type
158
     */
159
    protected function valueCanBeSimplified($value)
160
    {
161
        if (!is_array($value)) {
162
            return false;
163
        }
164
        if (count($value) != 1) {
165
            return false;
166
        }
167
        $data = array_shift($value);
168
        return is_string($data);
169
    }
170
171
    /**
172
     * Convert the children of the provided DOM element into an array.
173
     * Here, 'unique' means that all of the element names of the children are
174
     * different.  Since the element names will become the key of the
175
     * associative array that is returned, so duplicates are not supported.
176
     * If there are any duplicates, then an exception will be thrown.
177
     *
178
     * @param type $parentKey
179
     * @param type $element
180
     * @return type
181
     */
182
    protected function getUniqueChildren($parentKey, $element)
0 ignored issues
show
Unused Code introduced by
The parameter $parentKey is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
183
    {
184
        $children = $this->getNodeChildrenData($element);
185
        if ((count($children) == 1) && (is_string($children[0]))) {
186
            return [$element->nodeName => $children[0]];
187
        }
188
        $simplifiedChildren = [];
189
        foreach ($children as $key => $value) {
190
            if (is_numeric($key) && is_array($value) && (count($value) == 1)) {
191
                $valueKeys = array_keys($value);
192
                $key = $valueKeys[0];
193
                $value = array_shift($value);
194
            }
195
            if (array_key_exists($key, $simplifiedChildren)) {
196
                throw new \Exception("Cannot convert data from a DOM document to an array, because <$key> appears more than once, and is not wrapped in a <{$key}s> element.");
197
            }
198
            $simplifiedChildren[$key] = $value;
199
        }
200
        return $simplifiedChildren;
201
    }
202
}
203