Completed
Push — master ( fefe4d...d45b97 )
by Lars
01:59
created

SimpleXmlDom   F

Complexity

Total Complexity 99

Size/Duplication

Total Lines 733
Duplicated Lines 41.2 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 1.93%

Importance

Changes 0
Metric Value
wmc 99
lcom 1
cbo 5
dl 302
loc 733
ccs 4
cts 207
cp 0.0193
rs 1.867
c 0
b 0
f 0

35 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A __call() 0 10 2
A find() 0 4 1
A getAllAttributes() 13 13 3
A getAttribute() 0 10 2
A hasAttribute() 0 8 2
A innerXml() 0 4 1
A removeAttribute() 0 8 2
B replaceChildWithString() 37 37 8
A replaceNodeWithString() 7 36 5
A replaceTextWithString() 18 18 3
A setAttribute() 16 16 6
A text() 0 4 1
A xml() 0 4 1
A changeElementName() 25 25 4
A childNodes() 10 10 2
A findMulti() 0 4 1
A findOne() 0 4 1
A firstChild() 11 11 2
A getElementByClass() 0 4 1
A getElementById() 0 4 1
A getElementByTagName() 14 14 3
A getElementsById() 0 4 1
B getElementsByTagName() 31 31 6
A getNode() 0 4 1
A getXmlDomParser() 0 4 1
A innerHtml() 0 4 1
A isRemoved() 0 4 1
A lastChild() 11 11 2
A nextSibling() 11 11 2
A parentNode() 0 4 1
A previousSibling() 11 11 2
D val() 76 76 23
A getIterator() 11 11 3
A normalizeStringForComparision() 0 31 2

How to fix   Duplicated Code    Complexity   

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:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like SimpleXmlDom often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use SimpleXmlDom, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
declare(strict_types=1);
4
5
namespace voku\helper;
6
7
/** @noinspection PhpHierarchyChecksInspection */
8
class SimpleXmlDom extends AbstractSimpleXmlDom implements \IteratorAggregate, SimpleXmlDomInterface
9
{
10
    /**
11
     * @param \DOMElement|\DOMNode $node
12
     */
13 1
    public function __construct(\DOMNode $node)
14
    {
15 1
        $this->node = $node;
16 1
    }
17
18
    /**
19
     * @param string $name
20
     * @param array  $arguments
21
     *
22
     * @throws \BadMethodCallException
23
     *
24
     * @return SimpleXmlDomInterface|string|null
25
     */
26
    public function __call($name, $arguments)
27
    {
28
        $name = \strtolower($name);
29
30
        if (isset(self::$functionAliases[$name])) {
31
            return \call_user_func_array([$this, self::$functionAliases[$name]], $arguments);
32
        }
33
34
        throw new \BadMethodCallException('Method does not exist');
35
    }
36
37
    /**
38
     * Find list of nodes with a CSS selector.
39
     *
40
     * @param string   $selector
41
     * @param int|null $idx
42
     *
43
     * @return SimpleXmlDomInterface|SimpleXmlDomInterface[]|SimpleXmlDomNodeInterface
44
     */
45
    public function find(string $selector, $idx = null)
46
    {
47
        return $this->getXmlDomParser()->find($selector, $idx);
48
    }
49
50
    /**
51
     * Returns an array of attributes.
52
     *
53
     * @return array|null
54
     */
55 View Code Duplication
    public function getAllAttributes()
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...
56
    {
57
        if ($this->node->hasAttributes()) {
58
            $attributes = [];
59
            foreach ($this->node->attributes as $attr) {
60
                $attributes[$attr->name] = XmlDomParser::putReplacedBackToPreserveHtmlEntities($attr->value);
61
            }
62
63
            return $attributes;
64
        }
65
66
        return null;
67
    }
68
69
    /**
70
     * Return attribute value.
71
     *
72
     * @param string $name
73
     *
74
     * @return string
75
     */
76
    public function getAttribute(string $name): string
77
    {
78
        if ($this->node instanceof \DOMElement) {
79
            return XmlDomParser::putReplacedBackToPreserveHtmlEntities(
80
                $this->node->getAttribute($name)
81
            );
82
        }
83
84
        return '';
85
    }
86
87
    /**
88
     * Determine if an attribute exists on the element.
89
     *
90
     * @param string $name
91
     *
92
     * @return bool
93
     */
94
    public function hasAttribute(string $name): bool
95
    {
96
        if (!$this->node instanceof \DOMElement) {
97
            return false;
98
        }
99
100
        return $this->node->hasAttribute($name);
101
    }
102
103
    /**
104
     * Get dom node's inner html.
105
     *
106
     * @param bool $multiDecodeNewHtmlEntity
107
     *
108
     * @return string
109
     */
110
    public function innerXml(bool $multiDecodeNewHtmlEntity = false): string
111
    {
112
        return $this->getXmlDomParser()->innerXml($multiDecodeNewHtmlEntity);
113
    }
114
115
    /**
116
     * Remove attribute.
117
     *
118
     * @param string $name <p>The name of the html-attribute.</p>
119
     *
120
     * @return SimpleXmlDomInterface
121
     */
122
    public function removeAttribute(string $name): SimpleXmlDomInterface
123
    {
124
        if (\method_exists($this->node, 'removeAttribute')) {
125
            $this->node->removeAttribute($name);
0 ignored issues
show
Bug introduced by
The method removeAttribute does only exist in DOMElement, but not in DOMNode.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
126
        }
127
128
        return $this;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this; (voku\helper\SimpleXmlDom) is incompatible with the return type declared by the interface voku\helper\SimpleXmlDomInterface::removeAttribute of type self.

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...
129
    }
130
131
    /**
132
     * Replace child node.
133
     *
134
     * @param string $string
135
     *
136
     * @return SimpleXmlDomInterface
137
     */
138 View Code Duplication
    protected function replaceChildWithString(string $string): SimpleXmlDomInterface
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...
139
    {
140
        if (!empty($string)) {
141
            $newDocument = new XmlDomParser($string);
142
143
            $tmpDomString = $this->normalizeStringForComparision($newDocument);
144
            $tmpStr = $this->normalizeStringForComparision($string);
145
            if ($tmpDomString !== $tmpStr) {
146
                throw new \RuntimeException(
147
                    'Not valid HTML fragment!' . "\n" .
148
                    $tmpDomString . "\n" .
149
                    $tmpStr
150
                );
151
            }
152
        }
153
154
        if (\count($this->node->childNodes) > 0) {
155
            foreach ($this->node->childNodes as $node) {
156
                $this->node->removeChild($node);
157
            }
158
        }
159
160
        if (!empty($newDocument)) {
161
            $ownerDocument = $this->node->ownerDocument;
162
            if (
163
                $ownerDocument !== null
164
                &&
165
                $newDocument->getDocument()->documentElement !== null
166
            ) {
167
                $newNode = $ownerDocument->importNode($newDocument->getDocument()->documentElement, true);
168
                /** @noinspection UnusedFunctionResultInspection */
169
                $this->node->appendChild($newNode);
170
            }
171
        }
172
173
        return $this;
174
    }
175
176
    /**
177
     * Replace this node.
178
     *
179
     * @param string $string
180
     *
181
     * @return SimpleXmlDomInterface
182
     */
183
    protected function replaceNodeWithString(string $string): SimpleXmlDomInterface
184
    {
185
        if (empty($string)) {
186
            $this->node->parentNode->removeChild($this->node);
187
188
            return $this;
189
        }
190
191
        $newDocument = new XmlDomParser($string);
192
193
        $tmpDomOuterTextString = $this->normalizeStringForComparision($newDocument);
194
        $tmpStr = $this->normalizeStringForComparision($string);
195 View Code Duplication
        if ($tmpDomOuterTextString !== $tmpStr) {
0 ignored issues
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...
196
            throw new \RuntimeException(
197
                'Not valid HTML fragment!' . "\n"
198
                . $tmpDomOuterTextString . "\n" .
199
                $tmpStr
200
            );
201
        }
202
203
        $ownerDocument = $this->node->ownerDocument;
204
        if (
205
            $ownerDocument === null
206
            ||
207
            $newDocument->getDocument()->documentElement === null
208
        ) {
209
            return $this;
210
        }
211
212
        $newNode = $ownerDocument->importNode($newDocument->getDocument()->documentElement, true);
213
214
        $this->node->parentNode->replaceChild($newNode, $this->node);
215
        $this->node = $newNode;
216
217
        return $this;
218
    }
219
220
    /**
221
     * Replace this node with text
222
     *
223
     * @param string $string
224
     *
225
     * @return SimpleXmlDomInterface
226
     */
227 View Code Duplication
    protected function replaceTextWithString($string): SimpleXmlDomInterface
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...
228
    {
229
        if (empty($string)) {
230
            $this->node->parentNode->removeChild($this->node);
231
232
            return $this;
233
        }
234
235
        $ownerDocument = $this->node->ownerDocument;
236
        if ($ownerDocument !== null) {
237
            $newElement = $ownerDocument->createTextNode($string);
238
            $newNode = $ownerDocument->importNode($newElement, true);
239
            $this->node->parentNode->replaceChild($newNode, $this->node);
240
            $this->node = $newNode;
241
        }
242
243
        return $this;
244
    }
245
246
    /**
247
     * Set attribute value.
248
     *
249
     * @param string      $name       <p>The name of the html-attribute.</p>
250
     * @param string|null $value      <p>Set to NULL or empty string, to remove the attribute.</p>
251
     * @param bool        $strict     </p>
252
     *                                $value must be NULL, to remove the attribute,
253
     *                                so that you can set an empty string as attribute-value e.g. autofocus=""
254
     *                                </p>
255
     *
256
     * @return SimpleXmlDomInterface
257
     */
258 View Code Duplication
    public function setAttribute(string $name, $value = null, bool $strict = false): SimpleXmlDomInterface
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...
259
    {
260
        if (
261
            ($strict && $value === null)
262
            ||
263
            (!$strict && empty($value))
264
        ) {
265
            /** @noinspection UnusedFunctionResultInspection */
266
            $this->removeAttribute($name);
267
        } elseif (\method_exists($this->node, 'setAttribute')) {
268
            /** @noinspection UnusedFunctionResultInspection */
269
            $this->node->setAttribute($name, $value);
0 ignored issues
show
Bug introduced by
The method setAttribute does only exist in DOMElement, but not in DOMNode.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
270
        }
271
272
        return $this;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this; (voku\helper\SimpleXmlDom) is incompatible with the return type declared by the interface voku\helper\SimpleXmlDomInterface::setAttribute of type self.

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...
273
    }
274
275
    /**
276
     * Get dom node's plain text.
277
     *
278
     * @return string
279
     */
280
    public function text(): string
281
    {
282
        return $this->getXmlDomParser()->fixHtmlOutput($this->node->textContent);
283
    }
284
285
    /**
286
     * Get dom node's outer html.
287
     *
288
     * @param bool $multiDecodeNewHtmlEntity
289
     *
290
     * @return string
291
     */
292
    public function xml(bool $multiDecodeNewHtmlEntity = false): string
293
    {
294
        return $this->getXmlDomParser()->xml($multiDecodeNewHtmlEntity, false);
295
    }
296
297
    /**
298
     * Change the name of a tag in a "DOMNode".
299
     *
300
     * @param \DOMNode $node
301
     * @param string   $name
302
     *
303
     * @return \DOMElement|false
304
     *                          <p>DOMElement a new instance of class DOMElement or false
305
     *                          if an error occured.</p>
306
     */
307 View Code Duplication
    protected function changeElementName(\DOMNode $node, string $name)
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...
308
    {
309
        $ownerDocument = $node->ownerDocument;
310
        if ($ownerDocument) {
311
            $newNode = $ownerDocument->createElement($name);
312
        } else {
313
            return false;
314
        }
315
316
        foreach ($node->childNodes as $child) {
317
            $child = $ownerDocument->importNode($child, true);
318
            /** @noinspection UnusedFunctionResultInspection */
319
            $newNode->appendChild($child);
320
        }
321
322
        foreach ($node->attributes as $attrName => $attrNode) {
323
            /** @noinspection UnusedFunctionResultInspection */
324
            $newNode->setAttribute($attrName, $attrNode);
325
        }
326
327
        /** @noinspection UnusedFunctionResultInspection */
328
        $newNode->ownerDocument->replaceChild($newNode, $node);
329
330
        return $newNode;
331
    }
332
333
    /**
334
     * Returns children of node.
335
     *
336
     * @param int $idx
337
     *
338
     * @return SimpleXmlDomInterface|SimpleXmlDomInterface[]|SimpleXmlDomNodeInterface|null
339
     */
340 View Code Duplication
    public function childNodes(int $idx = -1)
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...
341
    {
342
        $nodeList = $this->getIterator();
343
344
        if ($idx === -1) {
345
            return $nodeList;
346
        }
347
348
        return $nodeList[$idx] ?? null;
349
    }
350
351
    /**
352
     * Find nodes with a CSS selector.
353
     *
354
     * @param string $selector
355
     *
356
     * @return SimpleXmlDomInterface[]|SimpleXmlDomNodeInterface
357
     */
358
    public function findMulti(string $selector): SimpleXmlDomNodeInterface
359
    {
360
        return $this->find($selector, null);
361
    }
362
363
    /**
364
     * Find one node with a CSS selector.
365
     *
366
     * @param string $selector
367
     *
368
     * @return SimpleXmlDomInterface
369
     */
370
    public function findOne(string $selector): SimpleXmlDomInterface
371
    {
372
        return $this->find($selector, 0);
373
    }
374
375
    /**
376
     * Returns the first child of node.
377
     *
378
     * @return SimpleXmlDomInterface|null
379
     */
380 View Code Duplication
    public function firstChild()
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...
381
    {
382
        /** @var \DOMNode|null $node */
383
        $node = $this->node->firstChild;
384
385
        if ($node === null) {
386
            return null;
387
        }
388
389
        return new static($node);
390
    }
391
392
    /**
393
     * Return elements by .class.
394
     *
395
     * @param string $class
396
     *
397
     * @return SimpleXmlDomInterface[]|SimpleXmlDomNodeInterface
398
     */
399
    public function getElementByClass(string $class): SimpleXmlDomNodeInterface
400
    {
401
        return $this->findMulti(".${class}");
402
    }
403
404
    /**
405
     * Return element by #id.
406
     *
407
     * @param string $id
408
     *
409
     * @return SimpleXmlDomInterface
410
     */
411
    public function getElementById(string $id): SimpleXmlDomInterface
412
    {
413
        return $this->findOne("#${id}");
414
    }
415
416
    /**
417
     * Return element by tag name.
418
     *
419
     * @param string $name
420
     *
421
     * @return SimpleXmlDomInterface
422
     */
423 View Code Duplication
    public function getElementByTagName(string $name): SimpleXmlDomInterface
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...
424
    {
425
        if ($this->node instanceof \DOMElement) {
426
            $node = $this->node->getElementsByTagName($name)->item(0);
427
        } else {
428
            $node = null;
429
        }
430
431
        if ($node === null) {
432
            return new SimpleXmlDomBlank();
433
        }
434
435
        return new static($node);
436
    }
437
438
    /**
439
     * Returns elements by #id.
440
     *
441
     * @param string   $id
442
     * @param int|null $idx
443
     *
444
     * @return SimpleXmlDomInterface|SimpleXmlDomInterface[]|SimpleXmlDomNodeInterface
445
     */
446
    public function getElementsById(string $id, $idx = null)
447
    {
448
        return $this->find("#${id}", $idx);
449
    }
450
451
    /**
452
     * Returns elements by tag name.
453
     *
454
     * @param string   $name
455
     * @param int|null $idx
456
     *
457
     * @return SimpleXmlDomInterface|SimpleXmlDomInterface[]|SimpleXmlDomNodeInterface
458
     */
459 View Code Duplication
    public function getElementsByTagName(string $name, $idx = null)
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...
460
    {
461
        if ($this->node instanceof \DOMElement) {
462
            $nodesList = $this->node->getElementsByTagName($name);
463
        } else {
464
            $nodesList = [];
465
        }
466
467
        $elements = new SimpleXmlDomNode();
468
469
        foreach ($nodesList as $node) {
470
            $elements[] = new static($node);
471
        }
472
473
        // return all elements
474
        if ($idx === null) {
475
            if (\count($elements) === 0) {
476
                return new SimpleXmlDomNodeBlank();
477
            }
478
479
            return $elements;
480
        }
481
482
        // handle negative values
483
        if ($idx < 0) {
484
            $idx = \count($elements) + $idx;
485
        }
486
487
        // return one element
488
        return $elements[$idx] ?? new SimpleXmlDomBlank();
489
    }
490
491
    /**
492
     * @return \DOMNode
493
     */
494
    public function getNode(): \DOMNode
495
    {
496 1
        return $this->node;
497
    }
498
499
    /**
500
     * Create a new "XmlDomParser"-object from the current context.
501
     *
502
     * @return XmlDomParser
503
     */
504
    public function getXmlDomParser(): XmlDomParser
505
    {
506
        return new XmlDomParser($this);
507
    }
508
509
    /**
510
     * Get dom node's inner html.
511
     *
512
     * @param bool $multiDecodeNewHtmlEntity
513
     *
514
     * @return string
515
     */
516
    public function innerHtml(bool $multiDecodeNewHtmlEntity = false): string
517
    {
518
        return $this->getXmlDomParser()->innerHtml($multiDecodeNewHtmlEntity);
519
    }
520
521
    /**
522
     * Nodes can get partially destroyed in which they're still an
523
     * actual DOM node (such as \DOMElement) but almost their entire
524
     * body is gone, including the `nodeType` attribute.
525
     *
526
     * @return bool true if node has been destroyed
527
     */
528
    public function isRemoved(): bool
529
    {
530
        return !isset($this->node->nodeType);
531
    }
532
533
    /**
534
     * Returns the last child of node.
535
     *
536
     * @return SimpleXmlDomInterface|null
537
     */
538 View Code Duplication
    public function lastChild()
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...
539
    {
540
        /** @var \DOMNode|null $node */
541
        $node = $this->node->lastChild;
542
543
        if ($node === null) {
544
            return null;
545
        }
546
547
        return new static($node);
548
    }
549
550
    /**
551
     * Returns the next sibling of node.
552
     *
553
     * @return SimpleXmlDomInterface|null
554
     */
555 View Code Duplication
    public function nextSibling()
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...
556
    {
557
        /** @var \DOMNode|null $node */
558
        $node = $this->node->nextSibling;
559
560
        if ($node === null) {
561
            return null;
562
        }
563
564
        return new static($node);
565
    }
566
567
    /**
568
     * Returns the parent of node.
569
     *
570
     * @return SimpleXmlDomInterface
571
     */
572
    public function parentNode(): SimpleXmlDomInterface
573
    {
574
        return new static($this->node->parentNode);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return new static($this->node->parentNode); (voku\helper\SimpleXmlDom) is incompatible with the return type declared by the interface voku\helper\SimpleXmlDomInterface::parentNode of type self.

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...
575
    }
576
577
    /**
578
     * Returns the previous sibling of node.
579
     *
580
     * @return SimpleXmlDomInterface|null
581
     */
582 View Code Duplication
    public function previousSibling()
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...
583
    {
584
        /** @var \DOMNode|null $node */
585
        $node = $this->node->previousSibling;
586
587
        if ($node === null) {
588
            return null;
589
        }
590
591
        return new static($node);
592
    }
593
594
    /**
595
     * @param string|string[]|null $value <p>
596
     *                                    null === get the current input value
597
     *                                    text === set a new input value
598
     *                                    </p>
599
     *
600
     * @return string|string[]|null
601
     */
602 View Code Duplication
    public function val($value = null)
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...
603
    {
604
        if ($value === null) {
605
            if (
606
                $this->tag === 'input'
0 ignored issues
show
Documentation introduced by
The property tag does not exist on object<voku\helper\SimpleXmlDom>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
607
                &&
608
                (
609
                    $this->getAttribute('type') === 'text'
610
                    ||
611
                    !$this->hasAttribute('type')
612
                )
613
            ) {
614
                return $this->getAttribute('value');
615
            }
616
617
            if (
618
                $this->hasAttribute('checked')
619
                &&
620
                \in_array($this->getAttribute('type'), ['checkbox', 'radio'], true)
621
            ) {
622
                return $this->getAttribute('value');
623
            }
624
625
            if ($this->node->nodeName === 'select') {
626
                $valuesFromDom = [];
627
                $options = $this->getElementsByTagName('option');
628
                if ($options instanceof SimpleXmlDomNode) {
629
                    foreach ($options as $option) {
630
                        if ($this->hasAttribute('checked')) {
631
                            /** @noinspection UnnecessaryCastingInspection */
632
                            $valuesFromDom[] = (string) $option->getAttribute('value');
633
                        }
634
                    }
635
                }
636
637
                if (\count($valuesFromDom) === 0) {
638
                    return null;
639
                }
640
641
                return $valuesFromDom;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $valuesFromDom; (array) is incompatible with the return type declared by the interface voku\helper\SimpleXmlDomInterface::val of type string|string[]|null.

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...
642
            }
643
644
            if ($this->node->nodeName === 'textarea') {
645
                return $this->node->nodeValue;
646
            }
647
        } else {
648
            /** @noinspection NestedPositiveIfStatementsInspection */
649
            if (\in_array($this->getAttribute('type'), ['checkbox', 'radio'], true)) {
650
                if ($value === $this->getAttribute('value')) {
651
                    /** @noinspection UnusedFunctionResultInspection */
652
                    $this->setAttribute('checked', 'checked');
653
                } else {
654
                    /** @noinspection UnusedFunctionResultInspection */
655
                    $this->removeAttribute('checked');
656
                }
657
            } elseif ($this->node instanceof \DOMElement && $this->node->nodeName === 'select') {
658
                foreach ($this->node->getElementsByTagName('option') as $option) {
659
                    /** @var \DOMElement $option */
660
                    if ($value === $option->getAttribute('value')) {
661
                        /** @noinspection UnusedFunctionResultInspection */
662
                        $option->setAttribute('selected', 'selected');
663
                    } else {
664
                        $option->removeAttribute('selected');
665
                    }
666
                }
667
            } elseif ($this->node->nodeName === 'input' && \is_string($value)) {
668
                // Set value for input elements
669
                /** @noinspection UnusedFunctionResultInspection */
670
                $this->setAttribute('value', $value);
671
            } elseif ($this->node->nodeName === 'textarea' && \is_string($value)) {
672
                $this->node->nodeValue = $value;
673
            }
674
        }
675
676
        return null;
677
    }
678
679
    /**
680
     * Retrieve an external iterator.
681
     *
682
     * @see  http://php.net/manual/en/iteratoraggregate.getiterator.php
683
     *
684
     * @return SimpleXmlDomNode
685
     *                           <p>
686
     *                              An instance of an object implementing <b>Iterator</b> or
687
     *                              <b>Traversable</b>
688
     *                           </p>
689
     */
690 View Code Duplication
    public function getIterator(): SimpleXmlDomNodeInterface
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...
691
    {
692
        $elements = new SimpleXmlDomNode();
693
        if ($this->node->hasChildNodes()) {
694
            foreach ($this->node->childNodes as $node) {
695
                $elements[] = new static($node);
696
            }
697
        }
698
699
        return $elements;
700
    }
701
702
    /**
703
     * Normalize the given input for comparision.
704
     *
705
     * @param string|XmlDomParser $input
706
     *
707
     * @return string
708
     */
709
    private function normalizeStringForComparision($input): string
710
    {
711
        if ($input instanceof XmlDomParser) {
712
            $string = $input->plaintext;
713
        } else {
714
            $string = (string) $input;
715
        }
716
717
        return
718
            \urlencode(
719
                \urldecode(
720
                    \trim(
721
                        \str_replace(
722
                            [
723
                                ' ',
724
                                "\n",
725
                                "\r",
726
                                '/>',
727
                            ],
728
                            [
729
                                '',
730
                                '',
731
                                '',
732
                                '>',
733
                            ],
734
                            \strtolower($string)
735
                        )
736
                    )
737
                )
738
            );
739
    }
740
}
741