GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — master ( 0b2d3d...31c470 )
by Christoph
03:14
created

HtmlPageCrawler::getCombinedText()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 9
ccs 5
cts 5
cp 1
rs 9.9666
c 0
b 0
f 0
cc 2
nc 2
nop 0
crap 2
1
<?php
2
namespace Wa72\HtmlPageDom;
3
4
use Symfony\Component\DomCrawler\Crawler;
5
6
/**
7
 * Extends \Symfony\Component\DomCrawler\Crawler by adding tree manipulation functions
8
 * for HTML documents inspired by jQuery such as html(), css(), append(), prepend(), before(),
9
 * addClass(), removeClass()
10
 *
11
 * @author Christoph Singer
12
 * @license MIT
13
 *
14
 */
15
class HtmlPageCrawler extends Crawler
0 ignored issues
show
Complexity introduced by
This class has 1060 lines of code which exceeds the configured maximum of 1000.

Really long classes often contain too much logic and violate the single responsibility principle.

We suggest to take a look at the “Code” section for options on how to refactor this code.

Loading history...
Complexity introduced by
This class has 49 public methods and attributes which exceeds the configured maximum of 45.

The number of this metric differs depending on the chosen design (inheritance vs. composition). For inheritance, the number should generally be a bit lower.

A high number indicates a reusable class. It might also make the class harder to change without breaking other classes though.

Loading history...
Complexity introduced by
This class has a complexity of 160 which exceeds the configured maximum of 50.

The class complexity is the sum of the complexity of all methods. A very high value is usually an indication that your class does not follow the single reponsibility principle and does more than one job.

Some resources for further reading:

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

Loading history...
16
{
17
    /**
18
     * the (internal) root element name used when importing html fragments
19
     * */
20
    const FRAGMENT_ROOT_TAGNAME = '_root';
21
22
    /**
23
     * Get an HtmlPageCrawler object from a HTML string, DOMNode, DOMNodeList or HtmlPageCrawler
24
     *
25
     * This is the equivalent to jQuery's $() function when used for wrapping DOMNodes or creating DOMElements from HTML code.
26
     *
27
     * @param string|HtmlPageCrawler|\DOMNode|\DOMNodeList|array $content
28
     * @return HtmlPageCrawler
29
     * @api
30
     */
31 17
    public static function create($content)
32
    {
33 17
        if ($content instanceof HtmlPageCrawler) {
34 3
            return $content;
35
        } else {
36 17
            return new HtmlPageCrawler($content);
37
        }
38
    }
39
40
    /**
41
     * Adds the specified class(es) to each element in the set of matched elements.
42
     *
43
     * @param string $name One or more space-separated classes to be added to the class attribute of each matched element.
44
     * @return HtmlPageCrawler $this for chaining
45
     * @api
46
     */
47 1
    public function addClass($name)
48
    {
49 1
        foreach ($this as $node) {
50 1
            if ($node instanceof \DOMElement) {
51
                /** @var \DOMElement $node */
52 1
                $classes = preg_split('/\s+/s', $node->getAttribute('class'));
53 1
                $found = false;
54 1
                $count = count($classes);
55 1
                for ($i = 0; $i < $count; $i++) {
56 1
                    if ($classes[$i] == $name) {
57 1
                        $found = true;
58
                    }
59
                }
60 1
                if (!$found) {
61 1
                    $classes[] = $name;
62 1
                    $node->setAttribute('class', trim(join(' ', $classes)));
63
                }
64
            }
65
        }
66 1
        return $this;
67
    }
68
69
    /**
70
     * Insert content, specified by the parameter, after each element in the set of matched elements.
71
     *
72
     * @param string|HtmlPageCrawler|\DOMNode|\DOMNodeList $content
73
     * @return HtmlPageCrawler $this for chaining
74
     * @api
75
     */
76 3
    public function after($content)
77
    {
78 3
        $content = self::create($content);
79 3
        $newnodes = array();
80 3
        foreach ($this as $i => $node) {
81
            /** @var \DOMNode $node */
82 3
            $refnode = $node->nextSibling;
83 3
            foreach ($content as $newnode) {
84
                /** @var \DOMNode $newnode */
85 3
                $newnode = static::importNewnode($newnode, $node, $i);
86 3
                if ($refnode === null) {
87 3
                    $node->parentNode->appendChild($newnode);
88
                } else {
89 1
                    $node->parentNode->insertBefore($newnode, $refnode);
90
                }
91 3
                $newnodes[] = $newnode;
92
            }
93
        }
94 3
        $content->clear();
95 3
        $content->add($newnodes);
96 3
        return $this;
97
    }
98
99
    /**
100
     * Insert HTML content as child nodes of each element after existing children
101
     *
102
     * @param string|HtmlPageCrawler|\DOMNode|\DOMNodeList $content HTML code fragment or DOMNode to append
103
     * @return HtmlPageCrawler $this for chaining
104
     * @api
105
     */
106 2
    public function append($content)
107
    {
108 2
        $content = self::create($content);
109 2
        $newnodes = array();
110 2
        foreach ($this as $i => $node) {
111
            /** @var \DOMNode $node */
112 2
            foreach ($content as $newnode) {
113
                /** @var \DOMNode $newnode */
114 2
                $newnode = static::importNewnode($newnode, $node, $i);
115
//                if ($newnode->ownerDocument !== $node->ownerDocument) {
116
//                    $newnode = $node->ownerDocument->importNode($newnode, true);
117
//                } else {
118
//                    if ($i > 0) {
119
//                        $newnode = $newnode->cloneNode(true);
120
//                    }
121
//                }
122 2
                $node->appendChild($newnode);
123 2
                $newnodes[] = $newnode;
124
            }
125
        }
126 2
        $content->clear();
127 2
        $content->add($newnodes);
128 2
        return $this;
129
    }
130
131
    /**
132
     * Insert every element in the set of matched elements to the end of the target.
133
     *
134
     * @param string|HtmlPageCrawler|\DOMNode|\DOMNodeList $element
135
     * @return \Wa72\HtmlPageDom\HtmlPageCrawler A new Crawler object containing all elements appended to the target elements
136
     * @api
137
     */
138 2
    public function appendTo($element)
139
    {
140 2
        $e = self::create($element);
141 2
        $newnodes = array();
142 2
        foreach ($e as $i => $node) {
143
            /** @var \DOMNode $node */
144 2
            foreach ($this as $newnode) {
145
                /** @var \DOMNode $newnode */
146 2
                if ($node !== $newnode) {
147 2
                    $newnode = static::importNewnode($newnode, $node, $i);
148 2
                    $node->appendChild($newnode);
149
                }
150 2
                $newnodes[] = $newnode;
151
            }
152
        }
153 2
        return self::create($newnodes);
154
    }
155
156
    /**
157
     * Returns the attribute value of the first node of the list, or sets an attribute on each element
158
     *
159
     * @see HtmlPageCrawler::getAttribute()
160
     * @see HtmlPageCrawler::setAttribute
161
     *
162
     * @param string $name
163
     * @param null|string $value
164
     * @return null|string|HtmlPageCrawler
165
     * @api
166
     */
167 2
    public function attr($name, $value = null)
168
    {
169 2
        if ($value === null) {
170 2
            return $this->getAttribute($name);
171
        } else {
172 1
            return $this->setAttribute($name, $value);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->setAttribute($name, $value); (Wa72\HtmlPageDom\HtmlPageCrawler) is incompatible with the return type of the parent method Symfony\Component\DomCrawler\Crawler::attr of type 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...
173
        }
174
    }
175
176
    /**
177
     * Sets an attribute on each element
178
     *
179
     * @param string $name
180
     * @param string $value
181
     * @return HtmlPageCrawler $this for chaining
182
     */
183 3
    public function setAttribute($name, $value)
184
    {
185 3
        foreach ($this as $node) {
186 3
            if ($node instanceof \DOMElement) {
187
                /** @var \DOMElement $node */
188 3
                $node->setAttribute($name, $value);
189
            }
190
        }
191 3
        return $this;
192
    }
193
194
    /**
195
     * Returns the attribute value of the first node of the list.
196
     *
197
     * @param string $name The attribute name
198
     * @return string|null The attribute value or null if the attribute does not exist
199
     * @throws \InvalidArgumentException When current node is empty
200
     *
201
     */
202 2
    public function getAttribute($name)
203
    {
204 2
        if (!count($this)) {
205 1
            throw new \InvalidArgumentException('The current node list is empty.');
206
        }
207 1
        $node = $this->getNode(0);
208 1
        return $node->hasAttribute($name) ? $node->getAttribute($name) : null;
209
    }
210
211
    /**
212
     * Insert content, specified by the parameter, before each element in the set of matched elements.
213
     *
214
     * @param string|HtmlPageCrawler|\DOMNode|\DOMNodeList $content
215
     * @return HtmlPageCrawler $this for chaining
216
     * @api
217
     */
218 2
    public function before($content)
219
    {
220 2
        $content = self::create($content);
221 2
        $newnodes = array();
222 2
        foreach ($this as $i => $node) {
223
            /** @var \DOMNode $node */
224 2
            foreach ($content as $newnode) {
225
                /** @var \DOMNode $newnode */
226 2
                if ($node !== $newnode) {
227 2
                    $newnode = static::importNewnode($newnode, $node, $i);
228 2
                    $node->parentNode->insertBefore($newnode, $node);
229 2
                    $newnodes[] = $newnode;
230
                }
231
            }
232
        }
233 2
        $content->clear();
234 2
        $content->add($newnodes);
235 2
        return $this;
236
    }
237
238
    /**
239
     * Create a deep copy of the set of matched elements.
240
     *
241
     * Equivalent to clone() in jQuery (clone is not a valid PHP function name)
242
     *
243
     * @return HtmlPageCrawler
244
     * @api
245
     */
246 1
    public function makeClone()
247
    {
248 1
        return clone $this;
249
    }
250
251 1
    public function __clone()
252
    {
253 1
        $newnodes = array();
254 1
        foreach ($this as $node) {
255
            /** @var \DOMNode $node */
256 1
            $newnodes[] = $node->cloneNode(true);
257
        }
258 1
        $this->clear();
259 1
        $this->add($newnodes);
260 1
    }
261
262
    /**
263
     * Get one CSS style property of the first element or set it for all elements in the list
264
     *
265
     * Function is here for compatibility with jQuery; it is the same as getStyle() and setStyle()
266
     *
267
     * @see HtmlPageCrawler::getStyle()
268
     * @see HtmlPageCrawler::setStyle()
269
     *
270
     * @param string $key The name of the style property
271
     * @param null|string $value The CSS value to set, or NULL to get the current value
272
     * @return HtmlPageCrawler|string If no param is provided, returns the CSS styles of the first element
273
     * @api
274
     */
275 1
    public function css($key, $value = null)
276
    {
277 1
        if (null === $value) {
278 1
            return $this->getStyle($key);
279
        } else {
280 1
            return $this->setStyle($key, $value);
281
        }
282
    }
283
284
    /**
285
     * get one CSS style property of the first element
286
     *
287
     * @param string $key name of the property
288
     * @return string|null value of the property
289
     */
290 1
    public function getStyle($key)
291
    {
292 1
        $styles = Helpers::cssStringToArray($this->getAttribute('style'));
293 1
        return (isset($styles[$key]) ? $styles[$key] : null);
294
    }
295
296
    /**
297
     * set one CSS style property for all elements in the list
298
     *
299
     * @param string $key name of the property
300
     * @param string $value value of the property
301
     * @return HtmlPageCrawler $this for chaining
302
     */
303 1
    public function setStyle($key, $value)
304
    {
305 1
        foreach ($this as $node) {
306 1
            if ($node instanceof \DOMElement) {
307
                /** @var \DOMElement $node */
308 1
                $styles = Helpers::cssStringToArray($node->getAttribute('style'));
309 1
                if ($value != '') {
310 1
                    $styles[$key] = $value;
311 1
                } elseif (isset($styles[$key])) {
312 1
                    unset($styles[$key]);
313
                }
314 1
                $node->setAttribute('style', Helpers::cssArrayToString($styles));
315
            }
316
        }
317 1
        return $this;
318
    }
319
320
    /**
321
     * Removes all child nodes and text from all nodes in set
322
     *
323
     * Equivalent to jQuery's empty() function which is not a valid function name in PHP
324
     * @return HtmlPageCrawler $this
325
     * @api
326
     */
327 1
    public function makeEmpty()
328
    {
329 1
        foreach ($this as $node) {
330 1
            $node->nodeValue = '';
331
        }
332 1
        return $this;
333
    }
334
335
    /**
336
     * Determine whether any of the matched elements are assigned the given class.
337
     *
338
     * @param string $name
339
     * @return bool
340
     * @api
341
     */
342 2
    public function hasClass($name)
343
    {
344 2
        foreach ($this as $node) {
345 2
            if ($node instanceof \DOMElement && $class = $node->getAttribute('class')) {
346 2
                $classes = preg_split('/\s+/s', $class);
347 2
                if (in_array($name, $classes)) {
348 2
                    return true;
349
                }
350
            }
351
        }
352 2
        return false;
353
    }
354
355
    /**
356
     * Set the HTML contents of each element
357
     *
358
     * @param string|HtmlPageCrawler|\DOMNode|\DOMNodeList $content HTML code fragment
359
     * @return HtmlPageCrawler $this for chaining
360
     */
361 3
    public function setInnerHtml($content)
362
    {
363 3
        $content = self::create($content);
364 3
        foreach ($this as $node) {
365 3
            $node->nodeValue = '';
366 3
            foreach ($content as $newnode) {
367
                /** @var \DOMNode $node */
368
                /** @var \DOMNode $newnode */
369 3
                $newnode = static::importNewnode($newnode, $node);
370 3
                $node->appendChild($newnode);
371
            }
372
        }
373 3
        return $this;
374
    }
375
376
    /**
377
     * Insert every element in the set of matched elements after the target.
378
     *
379
     * @param string|HtmlPageCrawler|\DOMNode|\DOMNodeList $element
380
     * @return \Wa72\HtmlPageDom\HtmlPageCrawler A new Crawler object containing all elements appended to the target elements
381
     * @api
382
     */
383 2
    public function insertAfter($element)
384
    {
385 2
        $e = self::create($element);
386 2
        $newnodes = array();
387 2
        foreach ($e as $i => $node) {
388
            /** @var \DOMNode $node */
389 2
            $refnode = $node->nextSibling;
390 2
            foreach ($this as $newnode) {
391
                /** @var \DOMNode $newnode */
392 2
                $newnode = static::importNewnode($newnode, $node, $i);
393 2
                if ($refnode === null) {
394 2
                    $node->parentNode->appendChild($newnode);
395
                } else {
396 1
                    $node->parentNode->insertBefore($newnode, $refnode);
397
                }
398 2
                $newnodes[] = $newnode;
399
            }
400
        }
401 2
        return self::create($newnodes);
402
    }
403
404
    /**
405
     * Insert every element in the set of matched elements before the target.
406
     *
407
     * @param string|HtmlPageCrawler|\DOMNode|\DOMNodeList $element
408
     * @return \Wa72\HtmlPageDom\HtmlPageCrawler A new Crawler object containing all elements appended to the target elements
409
     * @api
410
     */
411 2
    public function insertBefore($element)
412
    {
413 2
        $e = self::create($element);
414 2
        $newnodes = array();
415 2
        foreach ($e as $i => $node) {
416
            /** @var \DOMNode $node */
417 2
            foreach ($this as $newnode) {
418
                /** @var \DOMNode $newnode */
419 2
                $newnode = static::importNewnode($newnode, $node, $i);
420 2
                if ($newnode !== $node) {
421 2
                    $node->parentNode->insertBefore($newnode, $node);
422
                }
423 2
                $newnodes[] = $newnode;
424
            }
425
        }
426 2
        return self::create($newnodes);
427
    }
428
429
    /**
430
     * Insert content, specified by the parameter, to the beginning of each element in the set of matched elements.
431
     *
432
     * @param string|HtmlPageCrawler|\DOMNode|\DOMNodeList $content HTML code fragment
433
     * @return HtmlPageCrawler $this for chaining
434
     * @api
435
     */
436 2
    public function prepend($content)
437
    {
438 2
        $content = self::create($content);
439 2
        $newnodes = array();
440 2
        foreach ($this as $i => $node) {
441 2
            $refnode = $node->firstChild;
442
            /** @var \DOMNode $node */
443 2
            foreach ($content as $newnode) {
444
                /** @var \DOMNode $newnode */
445 2
                $newnode = static::importNewnode($newnode, $node, $i);
446 2
                if ($refnode === null) {
447 1
                    $node->appendChild($newnode);
448 2
                } else if ($refnode !== $newnode) {
449 2
                    $node->insertBefore($newnode, $refnode);
450
                }
451 2
                $newnodes[] = $newnode;
452
            }
453
        }
454 2
        $content->clear();
455 2
        $content->add($newnodes);
456 2
        return $this;
457
    }
458
459
    /**
460
     * Insert every element in the set of matched elements to the beginning of the target.
461
     *
462
     * @param string|HtmlPageCrawler|\DOMNode|\DOMNodeList $element
463
     * @return \Wa72\HtmlPageDom\HtmlPageCrawler A new Crawler object containing all elements prepended to the target elements
464
     * @api
465
     */
466 1
    public function prependTo($element)
467
    {
468 1
        $e = self::create($element);
469 1
        $newnodes = array();
470 1
        foreach ($e as $i => $node) {
471 1
            $refnode = $node->firstChild;
472
            /** @var \DOMNode $node */
473 1
            foreach ($this as $newnode) {
474
                /** @var \DOMNode $newnode */
475 1
                $newnode = static::importNewnode($newnode, $node, $i);
476 1
                if ($newnode !== $node) {
477 1
                    if ($refnode === null) {
478 1
                        $node->appendChild($newnode);
479
                    } else {
480 1
                        $node->insertBefore($newnode, $refnode);
481
                    }
482
                }
483 1
                $newnodes[] = $newnode;
484
            }
485
        }
486 1
        return self::create($newnodes);
487
    }
488
489
    /**
490
     * Remove the set of matched elements from the DOM.
491
     *
492
     * (as opposed to Crawler::clear() which detaches the nodes only from Crawler
493
     * but leaves them in the DOM)
494
     *
495
     * @api
496
     */
497 2
    public function remove()
498
    {
499 2
        foreach ($this as $node) {
500
            /**
501
             * @var \DOMNode $node
502
             */
503 2
            if ($node->parentNode instanceof \DOMElement) {
504 2
                $node->parentNode->removeChild($node);
505
            }
506
        }
507 2
        $this->clear();
508 2
    }
509
510
    /**
511
     * Remove an attribute from each element in the set of matched elements.
512
     *
513
     * Alias for removeAttribute for compatibility with jQuery
514
     *
515
     * @param string $name
516
     * @return HtmlPageCrawler
517
     * @api
518
     */
519 1
    public function removeAttr($name)
520
    {
521 1
        return $this->removeAttribute($name);
522
    }
523
524
    /**
525
     * Remove an attribute from each element in the set of matched elements.
526
     *
527
     * @param string $name
528
     * @return HtmlPageCrawler
529
     */
530 1
    public function removeAttribute($name)
531
    {
532 1
        foreach ($this as $node) {
533 1
            if ($node instanceof \DOMElement) {
534
                /** @var \DOMElement $node */
535 1
                if ($node->hasAttribute($name)) {
536 1
                    $node->removeAttribute($name);
537
                }
538
            }
539
        }
540 1
        return $this;
541
    }
542
543
    /**
544
     * Remove a class from each element in the list
545
     *
546
     * @param string $name
547
     * @return HtmlPageCrawler $this for chaining
548
     * @api
549
     */
550 2
    public function removeClass($name)
551
    {
552 2
        foreach ($this as $node) {
553 2
            if ($node instanceof \DOMElement) {
554
                /** @var \DOMElement $node */
555 2
                $classes = preg_split('/\s+/s', $node->getAttribute('class'));
556 2
                $count = count($classes);
557 2
                for ($i = 0; $i < $count; $i++) {
558 2
                    if ($classes[$i] == $name) {
559 2
                        unset($classes[$i]);
560
                    }
561
                }
562 2
                $node->setAttribute('class', trim(join(' ', $classes)));
563
            }
564
        }
565 2
        return $this;
566
    }
567
568
    /**
569
     * Replace each target element with the set of matched elements.
570
     *
571
     * @param string|HtmlPageCrawler|\DOMNode|\DOMNodeList $element
572
     * @return \Wa72\HtmlPageDom\HtmlPageCrawler A new Crawler object containing all elements appended to the target elements
573
     * @api
574
     */
575 2
    public function replaceAll($element)
576
    {
577 2
        $e = self::create($element);
578 2
        $newnodes = array();
579 2
        foreach ($e as $i => $node) {
580
            /** @var \DOMNode $node */
581 2
            $parent = $node->parentNode;
582 2
            $refnode  = $node->nextSibling;
583 2
            foreach ($this as $j => $newnode) {
584
                /** @var \DOMNode $newnode */
585 2
                $newnode = static::importNewnode($newnode, $node, $i);
586 2
                if ($j == 0) {
587 2
                    $parent->replaceChild($newnode, $node);
588
                } else {
589 1
                    $parent->insertBefore($newnode, $refnode);
590
                }
591 2
                $newnodes[] = $newnode;
592
            }
593
        }
594 2
        return self::create($newnodes);
595
    }
596
597
    /**
598
     * Replace each element in the set of matched elements with the provided new content and return the set of elements that was removed.
599
     *
600
     * @param string|HtmlPageCrawler|\DOMNode|\DOMNodeList $content
601
     * @return \Wa72\HtmlPageDom\HtmlPageCrawler $this for chaining
602
     * @api
603
     */
604 2
    public function replaceWith($content)
605
    {
606 2
        $content = self::create($content);
607 2
        $newnodes = array();
608 2
        foreach ($this as $i => $node) {
609
            /** @var \DOMNode $node */
610 2
            $parent = $node->parentNode;
611 2
            $refnode  = $node->nextSibling;
612 2
            foreach ($content as $j => $newnode) {
613
                /** @var \DOMNode $newnode */
614 2
                $newnode = static::importNewnode($newnode, $node, $i);
615 2
                if ($j == 0) {
616 2
                    $parent->replaceChild($newnode, $node);
617
                } else {
618 1
                    $parent->insertBefore($newnode, $refnode);
619
                }
620 2
                $newnodes[] = $newnode;
621
            }
622
        }
623 2
        $content->clear();
624 2
        $content->add($newnodes);
625 2
        return $this;
626
    }
627
628
    /**
629
     * Get the combined text contents of each element in the set of matched elements, including their descendants.
630
     * This is what the jQuery text() function does, contrary to the Crawler::text() method that returns only
631
     * the text of the first node.
632
     *
633
     * @return string
634
     * @api
635
     */
636 1
    public function getCombinedText()
637
    {
638 1
        $text = '';
639 1
        foreach ($this as $node) {
640
            /** @var \DOMNode $node */
641 1
            $text .= $node->nodeValue;
642
        }
643 1
        return $text;
644
    }
645
646
    /**
647
     * Set the text contents of the matched elements.
648
     *
649
     * @param string $text
650
     * @return HtmlPageCrawler
651
     * @api
652
     */
653 1
    public function setText($text)
654
    {
655 1
        foreach ($this as $node) {
656
            /** @var \DOMNode $node */
657 1
            $node->nodeValue = $text;
658
        }
659 1
        return $this;
660
    }
661
662
    /**
663
     * Add or remove one or more classes from each element in the set of matched elements, depending the class’s presence.
664
     *
665
     * @param string $classname One or more classnames separated by spaces
666
     * @return \Wa72\HtmlPageDom\HtmlPageCrawler $this for chaining
667
     * @api
668
     */
669 1
    public function toggleClass($classname)
670
    {
671 1
        $classes = explode(' ', $classname);
672 1
        foreach ($this as $i => $node) {
673 1
            $c = self::create($node);
674
            /** @var \DOMNode $node */
675 1
            foreach ($classes as $class) {
676 1
                if ($c->hasClass($class)) {
677 1
                    $c->removeClass($class);
678
                } else {
679 1
                    $c->addClass($class);
680
                }
681
            }
682
        }
683 1
        return $this;
684
    }
685
686
    /**
687
     * Remove the parents of the set of matched elements from the DOM, leaving the matched elements in their place.
688
     *
689
     * @return \Wa72\HtmlPageDom\HtmlPageCrawler $this for chaining
690
     * @api
691
     */
692 1
    public function unwrap()
693
    {
694 1
        $parents = array();
695 1
        foreach($this as $i => $node) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after FOREACH keyword; 0 found
Loading history...
696 1
            $parents[] = $node->parentNode;
697
        }
698
699 1
        self::create($parents)->unwrapInner();
700 1
        return $this;
701
    }
702
703
    /**
704
     * Remove the matched elements, but promote the children to take their place.
705
     *
706
     * @return \Wa72\HtmlPageDom\HtmlPageCrawler $this for chaining
707
     * @api
708
     */
709 2
    public function unwrapInner()
710
    {
711 2
        foreach($this as $i => $node) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after FOREACH keyword; 0 found
Loading history...
712 2
            if (!$node->parentNode instanceof \DOMElement) {
713 1
                throw new \InvalidArgumentException('DOMElement does not have a parent DOMElement node.');
714
            }
715
716
            /** @var \DOMNode[] $children */
717 2
            $children = iterator_to_array($node->childNodes);
718 2
            foreach ($children as $child) {
719 1
                $node->parentNode->insertBefore($child, $node);
720
            }
721
722 2
            $node->parentNode->removeChild($node);
723
        }
724 2
    }
725
726
727
    /**
728
     * Wrap an HTML structure around each element in the set of matched elements
729
     *
730
     * The HTML structure must contain only one root node, e.g.:
731
     * Works: <div><div></div></div>
732
     * Does not work: <div></div><div></div>
733
     *
734
     * @param string|HtmlPageCrawler|\DOMNode $wrappingElement
735
     * @return HtmlPageCrawler $this for chaining
736
     * @api
737
     */
738 1
    public function wrap($wrappingElement)
739
    {
740 1
        $content = self::create($wrappingElement);
741 1
        $newnodes = array();
742 1
        foreach ($this as $i => $node) {
743
            /** @var \DOMNode $node */
744 1
            $newnode = $content->getNode(0);
745
            /** @var \DOMNode $newnode */
746
//            $newnode = static::importNewnode($newnode, $node, $i);
747 1
            if ($newnode->ownerDocument !== $node->ownerDocument) {
748 1
                $newnode = $node->ownerDocument->importNode($newnode, true);
749
            } else {
750
                if ($i > 0) {
751
                    $newnode = $newnode->cloneNode(true);
752
                }
753
            }
754 1
            $oldnode = $node->parentNode->replaceChild($newnode, $node);
755 1
            while ($newnode->hasChildNodes()) {
756 1
                $elementFound = false;
757 1
                foreach ($newnode->childNodes as $child) {
758 1
                    if ($child instanceof \DOMElement) {
759 1
                        $newnode = $child;
760 1
                        $elementFound = true;
761 1
                        break;
762
                    }
763
                }
764 1
                if (!$elementFound) {
765 1
                    break;
766
                }
767
            }
768 1
            $newnode->appendChild($oldnode);
769 1
            $newnodes[] = $newnode;
770
        }
771 1
        $content->clear();
772 1
        $content->add($newnodes);
773 1
        return $this;
774
    }
775
776
    /**
777
     * Wrap an HTML structure around all elements in the set of matched elements.
778
     *
779
     * @param string|HtmlPageCrawler|\DOMNode|\DOMNodeList $content
780
     * @throws \LogicException
781
     * @return \Wa72\HtmlPageDom\HtmlPageCrawler $this for chaining
782
     * @api
783
     */
784 1
    public function wrapAll($content)
785
    {
786 1
        $content = self::create($content);
787 1
        $parent = $this->getNode(0)->parentNode;
788 1
        foreach ($this as $i => $node) {
789
            /** @var \DOMNode $node */
790 1
            if ($node->parentNode !== $parent) {
791 1
                throw new \LogicException('Nodes to be wrapped with wrapAll() must all have the same parent');
792
            }
793
        }
794
795 1
        $newnode = $content->getNode(0);
796
        /** @var \DOMNode $newnode */
797 1
        $newnode = static::importNewnode($newnode, $parent);
798
799 1
        $newnode = $parent->insertBefore($newnode,$this->getNode(0));
800 1
        $content->clear();
801 1
        $content->add($newnode);
802
803 1
        while ($newnode->hasChildNodes()) {
804 1
            $elementFound = false;
805 1
            foreach ($newnode->childNodes as $child) {
806 1
                if ($child instanceof \DOMElement) {
807 1
                    $newnode = $child;
808 1
                    $elementFound = true;
809 1
                    break;
810
                }
811
            }
812 1
            if (!$elementFound) {
813
                break;
814
            }
815
        }
816 1
        foreach ($this as $i => $node) {
817
            /** @var \DOMNode $node */
818 1
            $newnode->appendChild($node);
819
        }
820 1
        return $this;
821
    }
822
823
    /**
824
     * Wrap an HTML structure around the content of each element in the set of matched elements.
825
     *
826
     * @param string|HtmlPageCrawler|\DOMNode|\DOMNodeList $content
827
     * @return \Wa72\HtmlPageDom\HtmlPageCrawler $this for chaining
828
     * @api
829
     */
830 1
    public function wrapInner($content)
831
    {
832 1
        foreach ($this as $i => $node) {
833
            /** @var \DOMNode $node */
834 1
            self::create($node->childNodes)->wrapAll($content);
835
        }
836 1
        return $this;
837
    }
838
839
    /**
840
     * Get the HTML code fragment of all elements and their contents.
841
     *
842
     * If the first node contains a complete HTML document return only
843
     * the full code of this document.
844
     *
845
     * @return string HTML code (fragment)
846
     * @api
847
     */
848 8
    public function saveHTML()
849
    {
850 8
        if ($this->isHtmlDocument()) {
851 1
            return $this->getDOMDocument()->saveHTML();
852
        } else {
853 8
            $doc = new \DOMDocument('1.0', 'UTF-8');
854 8
            $root = $doc->appendChild($doc->createElement('_root'));
855 8
            foreach ($this as $node) {
856 8
                $root->appendChild($doc->importNode($node, true));
857
            }
858 8
            $html = trim($doc->saveHTML());
859 8
            return preg_replace('@^<'.self::FRAGMENT_ROOT_TAGNAME.'[^>]*>|</'.self::FRAGMENT_ROOT_TAGNAME.'>$@', '', $html);
860
        }
861
    }
862
863 4
    public function __toString()
864
    {
865 4
        return $this->saveHTML();
866
    }
867
868
    /**
869
     * checks whether the first node contains a complete html document
870
     * (as opposed to a document fragment)
871
     *
872
     * @return boolean
873
     */
874 8
    public function isHtmlDocument()
875
    {
876 8
        $node = $this->getNode(0);
877 8
        if ($node instanceof \DOMElement
878 8
            && $node->ownerDocument instanceof \DOMDocument
879 8
            && $node->ownerDocument->documentElement === $node
880 8
            && $node->nodeName == 'html'
881
        ) {
882 1
            return true;
883
        } else {
884 8
            return false;
885
        }
886
    }
887
888
    /**
889
     * get ownerDocument of the first element
890
     *
891
     * @return \DOMDocument|null
892
     */
893 1
    public function getDOMDocument()
894
    {
895 1
        $node = $this->getNode(0);
896 1
        $r = null;
897 1
        if ($node instanceof \DOMElement
898 1
            && $node->ownerDocument instanceof \DOMDocument
899
        ) {
900 1
            $r = $node->ownerDocument;
901
        }
902 1
        return $r;
903
    }
904
905
    /**
906
     * Filters the list of nodes with a CSS selector.
907
     *
908
     * @param string $selector
909
     * @return HtmlPageCrawler
910
     */
911 8
    public function filter($selector)
912
    {
913 8
        return parent::filter($selector);
914
    }
915
916
    /**
917
     * Filters the list of nodes with an XPath expression.
918
     *
919
     * @param string $xpath An XPath expression
920
     *
921
     * @return HtmlPageCrawler A new instance of Crawler with the filtered list of nodes
922
     *
923
     * @api
924
     */
925 2
    public function filterXPath($xpath)
926
    {
927 2
        return parent::filterXPath($xpath);
928
    }
929
930
    /**
931
     * Adds HTML/XML content to the HtmlPageCrawler object (but not to the DOM of an already attached node).
932
     *
933
     * Function overriden from Crawler because HTML fragments are always added as complete documents there
934
     *
935
     *
936
     * @param string      $content A string to parse as HTML/XML
937
     * @param null|string $type    The content type of the string
938
     *
939
     * @return null|void
940
     */
941 17
    public function addContent($content, $type = null)
942
    {
943 17
        if (empty($type)) {
944 17
            $type = 'text/html;charset=UTF-8';
945
        }
946 17
        if (substr($type, 0, 9) == 'text/html' && !preg_match('/<html\b[^>]*>/i', $content)) {
947
            // string contains no <html> Tag => no complete document but an HTML fragment!
948 16
            $this->addHtmlFragment($content);
949
        } else {
950 2
            parent::addContent($content, $type);
951
        }
952 17
    }
953
954 15
    public function addHtmlFragment($content, $charset = 'UTF-8')
955
    {
956 15
        $d = new \DOMDocument('1.0', $charset);
957 15
        $root = $d->appendChild($d->createElement(self::FRAGMENT_ROOT_TAGNAME));
958 15
        $bodynode = Helpers::getBodyNodeFromHtmlFragment($content, $charset);
959 15
        foreach ($bodynode->childNodes as $child) {
960 15
            $inode = $root->appendChild($d->importNode($child, true));
961 15
            if ($inode) {
962 15
                $this->addNode($inode);
963
            }
964
        }
965 15
    }
966
967
    /**
968
     * returns the first node
969
     * deprecated, use getNode(0) instead
970
     *
971
     * @return \DOMNode|null
972
     * @deprecated
973
     * @see Crawler::getNode
974
     */
975 1
    public function getFirstNode()
976
    {
977 1
        return $this->getNode(0);
978
    }
979
980
    /**
981
     * @param int $position
982
     *
983
     * overridden from Crawler because it is not public in Symfony 2.3
984
     * TODO: throw away as soon as we don't need to support SF 2.3 any more
985
     *
986
     * @return \DOMElement|null
987
     */
988 13
    public function getNode($position)
989
    {
990 13
        return parent::getNode($position);
991
    }
992
993
    /**
994
     * Returns the node name of the first node of the list.
995
     *
996
     * in Crawler (parent), this function will be available starting with 2.6.0,
997
     * therefore this method be removed from here as soon as we don't need to keep compatibility
998
     * with Symfony < 2.6
999
     *
1000
     * TODO: throw away as soon as we don't need to support SF 2.3 any more
1001
     *
1002
     * @return string The node name
1003
     *
1004
     * @throws \InvalidArgumentException When current node is empty
1005
     */
1006 1
    public function nodeName()
1007
    {
1008 1
        if (!count($this)) {
1009
            throw new \InvalidArgumentException('The current node list is empty.');
1010
        }
1011 1
        return $this->getNode(0)->nodeName;
1012
    }
1013
1014
    /**
1015
     * Adds a node to the current list of nodes.
1016
     *
1017
     * This method uses the appropriate specialized add*() method based
1018
     * on the type of the argument.
1019
     *
1020
     * Overwritten from parent to allow Crawler to be added
1021
     *
1022
     * @param null|\DOMNodeList|array|\DOMNode|Crawler $node A node
1023
     *
1024
     * @api
1025
     */
1026 28
    public function add($node)
1027
    {
1028 28
        if ($node instanceof Crawler) {
1029 1
            foreach ($node as $childnode) {
1030 1
                $this->addNode($childnode);
1031
            }
1032
        } else {
1033 28
            parent::add($node);
1034
        }
1035 28
    }
1036
1037
    /**
1038
     * @param \DOMNode $newnode
1039
     * @param \DOMNode $referencenode
1040
     * @param int $clone
1041
     * @return \DOMNode
1042
     */
1043 6
    protected static function importNewnode(\DOMNode $newnode, \DOMNode $referencenode, $clone = 0) {
1044 6
        if ($newnode->ownerDocument !== $referencenode->ownerDocument) {
1045 5
            $newnode = $referencenode->ownerDocument->importNode($newnode, true);
1046
        } else {
1047 2
            if ($clone > 0) {
1048
                $newnode = $newnode->cloneNode(true);
1049
            }
1050
        }
1051 6
        return $newnode;
1052
    }
1053
1054
    /**
1055
     * Checks whether the first node in the set is disconnected (has no parent node)
1056
     *
1057
     * @return bool
1058
     */
1059 1
    public function isDisconnected()
1060
    {
1061 1
        $parent = $this->getNode(0)->parentNode;
1062 1
        return ($parent == null || $parent->tagName == self::FRAGMENT_ROOT_TAGNAME);
1063
    }
1064
1065 1
    public function __get($name)
1066
    {
1067
        switch ($name) {
1068 1
            case 'count':
1069 1
            case 'length':
1070 1
                return count($this);
1071
        }
1072 1
        throw new \Exception('No such property ' . $name);
1073
    }
1074
}
1075