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 ( 4f9297...0b2d3d )
by Christoph
11:22 queued 03:34
created

HtmlPageCrawler::wrap()   B

Complexity

Conditions 8
Paths 22

Size

Total Lines 37

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 26
CRAP Score 8.0707

Importance

Changes 0
Metric Value
dl 0
loc 37
ccs 26
cts 29
cp 0.8966
rs 8.0835
c 0
b 0
f 0
cc 8
nc 22
nop 1
crap 8.0707
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 50 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 1104 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 a complexity of 164 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 18
    public static function create($content)
32
    {
33 18
        if ($content instanceof HtmlPageCrawler) {
34 3
            return $content;
35
        } else {
36 18
            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 1
                    }
59 1
                }
60 1
                if (!$found) {
61 1
                    $classes[] = $name;
62 1
                    $node->setAttribute('class', trim(join(' ', $classes)));
63 1
                }
64 1
            }
65 1
        }
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 3
                } else {
89 1
                    $node->parentNode->insertBefore($newnode, $refnode);
90
                }
91 3
                $newnodes[] = $newnode;
92 3
            }
93 3
        }
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 2
            }
125 2
        }
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 2
                }
150 2
                $newnodes[] = $newnode;
151 2
            }
152 2
        }
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 3
            }
190 3
        }
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 2
                }
231 2
            }
232 2
        }
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 1
        }
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 1
                }
314 1
                $node->setAttribute('style', Helpers::cssArrayToString($styles));
315 1
            }
316 1
        }
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 1
        }
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 1
            }
351 2
        }
352 2
        return false;
353
    }
354
355
    /**
356
     * Get the HTML contents of the first element in the set of matched elements
357
     * or set the HTML contents of every matched element.
358
     *
359
     * Function is here for compatibility with jQuery: When called with a parameter, it is
360
     * equivalent to setInnerHtml(), without parameter it is the same as getInnerHtml()
361
     *
362
     * @see HtmlPageCrawler::setInnerHtml()
363
     * @see HtmlPageCrawler::getInnerHtml()
364
     *
365
     * @param string|HtmlPageCrawler|\DOMNode|\DOMNodeList|null $html The HTML content to set, or NULL to get the current content
366
     *
367
     * @return HtmlPageCrawler|string If no param is provided, returns the HTML content of the first element
368
     * @api
369
     */
370 1
    public function html($html = null)
371
    {
372 1
        if (null === $html) {
373 1
            return $this->getInnerHtml();
374
        } else {
375 1
            $this->setInnerHtml($html);
376 1
            return $this;
377
        }
378
    }
379
380
    /**
381
     * Get the innerHTML contents of the first element
382
     *
383
     * @return string HTML code fragment
384
     */
385 4
    public function getInnerHtml()
386
    {
387 4
        $node = $this->getNode(0);
388 4
        if ($node instanceof \DOMNode) {
389 3
            $doc = new \DOMDocument('1.0', 'UTF-8');
390 3
            $doc->appendChild($doc->importNode($node, true));
391 3
            $html = trim($doc->saveHTML());
392 3
            $tag = $node->nodeName;
393 3
            return preg_replace('@^<' . $tag . '[^>]*>|</' . $tag . '>$@', '', $html);
394
        } else {
395 1
            return '';
396
        }
397
    }
398
399
    /**
400
     * Set the HTML contents of each element
401
     *
402
     * @param string|HtmlPageCrawler|\DOMNode|\DOMNodeList $content HTML code fragment
403
     * @return HtmlPageCrawler $this for chaining
404
     */
405 3
    public function setInnerHtml($content)
406
    {
407 3
        $content = self::create($content);
408 3
        foreach ($this as $node) {
409 3
            $node->nodeValue = '';
410 3
            foreach ($content as $newnode) {
411
                /** @var \DOMNode $node */
412
                /** @var \DOMNode $newnode */
413 3
                $newnode = static::importNewnode($newnode, $node);
414 3
                $node->appendChild($newnode);
415 3
            }
416 3
        }
417 3
        return $this;
418
    }
419
420
    /**
421
     * Insert every element in the set of matched elements after the target.
422
     *
423
     * @param string|HtmlPageCrawler|\DOMNode|\DOMNodeList $element
424
     * @return \Wa72\HtmlPageDom\HtmlPageCrawler A new Crawler object containing all elements appended to the target elements
425
     * @api
426
     */
427 2
    public function insertAfter($element)
428
    {
429 2
        $e = self::create($element);
430 2
        $newnodes = array();
431 2
        foreach ($e as $i => $node) {
432
            /** @var \DOMNode $node */
433 2
            $refnode = $node->nextSibling;
434 2
            foreach ($this as $newnode) {
435
                /** @var \DOMNode $newnode */
436 2
                $newnode = static::importNewnode($newnode, $node, $i);
437 2
                if ($refnode === null) {
438 2
                    $node->parentNode->appendChild($newnode);
439 2
                } else {
440 1
                    $node->parentNode->insertBefore($newnode, $refnode);
441
                }
442 2
                $newnodes[] = $newnode;
443 2
            }
444 2
        }
445 2
        return self::create($newnodes);
446
    }
447
448
    /**
449
     * Insert every element in the set of matched elements before the target.
450
     *
451
     * @param string|HtmlPageCrawler|\DOMNode|\DOMNodeList $element
452
     * @return \Wa72\HtmlPageDom\HtmlPageCrawler A new Crawler object containing all elements appended to the target elements
453
     * @api
454
     */
455 2
    public function insertBefore($element)
456
    {
457 2
        $e = self::create($element);
458 2
        $newnodes = array();
459 2
        foreach ($e as $i => $node) {
460
            /** @var \DOMNode $node */
461 2
            foreach ($this as $newnode) {
462
                /** @var \DOMNode $newnode */
463 2
                $newnode = static::importNewnode($newnode, $node, $i);
464 2
                if ($newnode !== $node) {
465 2
                    $node->parentNode->insertBefore($newnode, $node);
466 2
                }
467 2
                $newnodes[] = $newnode;
468 2
            }
469 2
        }
470 2
        return self::create($newnodes);
471
    }
472
473
    /**
474
     * Insert content, specified by the parameter, to the beginning of each element in the set of matched elements.
475
     *
476
     * @param string|HtmlPageCrawler|\DOMNode|\DOMNodeList $content HTML code fragment
477
     * @return HtmlPageCrawler $this for chaining
478
     * @api
479
     */
480 2
    public function prepend($content)
481
    {
482 2
        $content = self::create($content);
483 2
        $newnodes = array();
484 2
        foreach ($this as $i => $node) {
485 2
            $refnode = $node->firstChild;
486
            /** @var \DOMNode $node */
487 2
            foreach ($content as $newnode) {
488
                /** @var \DOMNode $newnode */
489 2
                $newnode = static::importNewnode($newnode, $node, $i);
490 2
                if ($refnode === null) {
491 1
                    $node->appendChild($newnode);
492 2
                } else if ($refnode !== $newnode) {
493 2
                    $node->insertBefore($newnode, $refnode);
494 2
                }
495 2
                $newnodes[] = $newnode;
496 2
            }
497 2
        }
498 2
        $content->clear();
499 2
        $content->add($newnodes);
500 2
        return $this;
501
    }
502
503
    /**
504
     * Insert every element in the set of matched elements to the beginning of the target.
505
     *
506
     * @param string|HtmlPageCrawler|\DOMNode|\DOMNodeList $element
507
     * @return \Wa72\HtmlPageDom\HtmlPageCrawler A new Crawler object containing all elements prepended to the target elements
508
     * @api
509
     */
510 1
    public function prependTo($element)
511
    {
512 1
        $e = self::create($element);
513 1
        $newnodes = array();
514 1
        foreach ($e as $i => $node) {
515 1
            $refnode = $node->firstChild;
516
            /** @var \DOMNode $node */
517 1
            foreach ($this as $newnode) {
518
                /** @var \DOMNode $newnode */
519 1
                $newnode = static::importNewnode($newnode, $node, $i);
520 1
                if ($newnode !== $node) {
521 1
                    if ($refnode === null) {
522 1
                        $node->appendChild($newnode);
523 1
                    } else {
524 1
                        $node->insertBefore($newnode, $refnode);
525
                    }
526 1
                }
527 1
                $newnodes[] = $newnode;
528 1
            }
529 1
        }
530 1
        return self::create($newnodes);
531
    }
532
533
    /**
534
     * Remove the set of matched elements from the DOM.
535
     *
536
     * (as opposed to Crawler::clear() which detaches the nodes only from Crawler
537
     * but leaves them in the DOM)
538
     *
539
     * @api
540
     */
541 2
    public function remove()
542
    {
543 2
        foreach ($this as $node) {
544
            /**
545
             * @var \DOMNode $node
546
             */
547 2
            if ($node->parentNode instanceof \DOMElement) {
548 2
                $node->parentNode->removeChild($node);
549 2
            }
550 2
        }
551 2
        $this->clear();
552 2
    }
553
554
    /**
555
     * Remove an attribute from each element in the set of matched elements.
556
     *
557
     * Alias for removeAttribute for compatibility with jQuery
558
     *
559
     * @param string $name
560
     * @return HtmlPageCrawler
561
     * @api
562
     */
563 1
    public function removeAttr($name)
564
    {
565 1
        return $this->removeAttribute($name);
566
    }
567
568
    /**
569
     * Remove an attribute from each element in the set of matched elements.
570
     *
571
     * @param string $name
572
     * @return HtmlPageCrawler
573
     */
574 1
    public function removeAttribute($name)
575
    {
576 1
        foreach ($this as $node) {
577 1
            if ($node instanceof \DOMElement) {
578
                /** @var \DOMElement $node */
579 1
                if ($node->hasAttribute($name)) {
580 1
                    $node->removeAttribute($name);
581 1
                }
582 1
            }
583 1
        }
584 1
        return $this;
585
    }
586
587
    /**
588
     * Remove a class from each element in the list
589
     *
590
     * @param string $name
591
     * @return HtmlPageCrawler $this for chaining
592
     * @api
593
     */
594 2
    public function removeClass($name)
595
    {
596 2
        foreach ($this as $node) {
597 2
            if ($node instanceof \DOMElement) {
598
                /** @var \DOMElement $node */
599 2
                $classes = preg_split('/\s+/s', $node->getAttribute('class'));
600 2
                $count = count($classes);
601 2
                for ($i = 0; $i < $count; $i++) {
602 2
                    if ($classes[$i] == $name) {
603 2
                        unset($classes[$i]);
604 2
                    }
605 2
                }
606 2
                $node->setAttribute('class', trim(join(' ', $classes)));
607 2
            }
608 2
        }
609 2
        return $this;
610
    }
611
612
    /**
613
     * Replace each target element with the set of matched elements.
614
     *
615
     * @param string|HtmlPageCrawler|\DOMNode|\DOMNodeList $element
616
     * @return \Wa72\HtmlPageDom\HtmlPageCrawler A new Crawler object containing all elements appended to the target elements
617
     * @api
618
     */
619 2
    public function replaceAll($element)
620
    {
621 2
        $e = self::create($element);
622 2
        $newnodes = array();
623 2
        foreach ($e as $i => $node) {
624
            /** @var \DOMNode $node */
625 2
            $parent = $node->parentNode;
626 2
            $refnode  = $node->nextSibling;
627 2
            foreach ($this as $j => $newnode) {
628
                /** @var \DOMNode $newnode */
629 2
                $newnode = static::importNewnode($newnode, $node, $i);
630 2
                if ($j == 0) {
631 2
                    $parent->replaceChild($newnode, $node);
632 2
                } else {
633 1
                    $parent->insertBefore($newnode, $refnode);
634
                }
635 2
                $newnodes[] = $newnode;
636 2
            }
637 2
        }
638 2
        return self::create($newnodes);
639
    }
640
641
    /**
642
     * Replace each element in the set of matched elements with the provided new content and return the set of elements that was removed.
643
     *
644
     * @param string|HtmlPageCrawler|\DOMNode|\DOMNodeList $content
645
     * @return \Wa72\HtmlPageDom\HtmlPageCrawler $this for chaining
646
     * @api
647
     */
648 2
    public function replaceWith($content)
649
    {
650 2
        $content = self::create($content);
651 2
        $newnodes = array();
652 2
        foreach ($this as $i => $node) {
653
            /** @var \DOMNode $node */
654 2
            $parent = $node->parentNode;
655 2
            $refnode  = $node->nextSibling;
656 2
            foreach ($content as $j => $newnode) {
657
                /** @var \DOMNode $newnode */
658 2
                $newnode = static::importNewnode($newnode, $node, $i);
659 2
                if ($j == 0) {
660 2
                    $parent->replaceChild($newnode, $node);
661 2
                } else {
662 1
                    $parent->insertBefore($newnode, $refnode);
663
                }
664 2
                $newnodes[] = $newnode;
665 2
            }
666 2
        }
667 2
        $content->clear();
668 2
        $content->add($newnodes);
669 2
        return $this;
670
    }
671
672
    /**
673
     * Get the combined text contents of each element in the set of matched elements, including their descendants,
674
     * or set the text contents of the matched elements.
675
     *
676
     * ATTENTION: Contrary to the parent Crawler class, which returns the text from the first element only,
677
     * this functions returns the combined text of all elements (as jQuery does). If this is not what you need you
678
     * must call ->first() before calling ->text(), e.g.
679
     *
680
     * in Symfony\DOMCrawler\Crawler: $c->filter('p')->text() returns the text of the first paragraph only
681
     * in HtmlPageCrawler you need to call: $c->filter('p')->first()->text()
682
     *
683
     * @param null|string $text
684
     * @return string|HtmlPageCrawler
685
     * @api
686
     */
687 1
    public function text($text = null)
688
    {
689 1
        if ($text === null) {
690 1
            $text = '';
691 1
            foreach ($this as $node) {
692
                /** @var \DOMNode $node */
693 1
                $text .= $node->nodeValue;
694 1
            }
695 1
            return $text;
696
        } else {
697 1
            foreach ($this as $node) {
698
                /** @var \DOMNode $node */
699 1
                $node->nodeValue = $text;
700 1
            }
701 1
            return $this;
702
        }
703
    }
704
705
706
    /**
707
     * Add or remove one or more classes from each element in the set of matched elements, depending the class’s presence.
708
     *
709
     * @param string $classname One or more classnames separated by spaces
710
     * @return \Wa72\HtmlPageDom\HtmlPageCrawler $this for chaining
711
     * @api
712
     */
713 1
    public function toggleClass($classname)
714
    {
715 1
        $classes = explode(' ', $classname);
716 1
        foreach ($this as $i => $node) {
717 1
            $c = self::create($node);
718
            /** @var \DOMNode $node */
719 1
            foreach ($classes as $class) {
720 1
                if ($c->hasClass($class)) {
721 1
                    $c->removeClass($class);
722 1
                } else {
723 1
                    $c->addClass($class);
724
                }
725 1
            }
726 1
        }
727 1
        return $this;
728
    }
729
730
    /**
731
     * Remove the parents of the set of matched elements from the DOM, leaving the matched elements in their place.
732
     *
733
     * @return \Wa72\HtmlPageDom\HtmlPageCrawler $this for chaining
734
     * @api
735
     */
736 1
    public function unwrap()
737
    {
738 1
        $parents = array();
739 1
        foreach($this as $i => $node) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after FOREACH keyword; 0 found
Loading history...
740 1
            $parents[] = $node->parentNode;
741 1
        }
742
743 1
        self::create($parents)->unwrapInner();
744 1
        return $this;
745
    }
746
747
    /**
748
     * Remove the matched elements, but promote the children to take their place.
749
     *
750
     * @return \Wa72\HtmlPageDom\HtmlPageCrawler $this for chaining
751
     * @api
752
     */
753 2
    public function unwrapInner()
754
    {
755 2
        foreach($this as $i => $node) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after FOREACH keyword; 0 found
Loading history...
756 2
            if (!$node->parentNode instanceof \DOMElement) {
757 1
                throw new \InvalidArgumentException('DOMElement does not have a parent DOMElement node.');
758
            }
759
760
            /** @var \DOMNode[] $children */
761 2
            $children = iterator_to_array($node->childNodes);
762 2
            foreach ($children as $child) {
763 1
                $node->parentNode->insertBefore($child, $node);
764 2
            }
765
766 2
            $node->parentNode->removeChild($node);
767 2
        }
768 2
    }
769
770
771
    /**
772
     * Wrap an HTML structure around each element in the set of matched elements
773
     *
774
     * The HTML structure must contain only one root node, e.g.:
775
     * Works: <div><div></div></div>
776
     * Does not work: <div></div><div></div>
777
     *
778
     * @param string|HtmlPageCrawler|\DOMNode $wrappingElement
779
     * @return HtmlPageCrawler $this for chaining
780
     * @api
781
     */
782 1
    public function wrap($wrappingElement)
783
    {
784 1
        $content = self::create($wrappingElement);
785 1
        $newnodes = array();
786 1
        foreach ($this as $i => $node) {
787
            /** @var \DOMNode $node */
788 1
            $newnode = $content->getNode(0);
789
            /** @var \DOMNode $newnode */
790
//            $newnode = static::importNewnode($newnode, $node, $i);
791 1
            if ($newnode->ownerDocument !== $node->ownerDocument) {
792 1
                $newnode = $node->ownerDocument->importNode($newnode, true);
793 1
            } else {
794
                if ($i > 0) {
795
                    $newnode = $newnode->cloneNode(true);
796
                }
797
            }
798 1
            $oldnode = $node->parentNode->replaceChild($newnode, $node);
799 1
            while ($newnode->hasChildNodes()) {
800 1
                $elementFound = false;
801 1
                foreach ($newnode->childNodes as $child) {
802 1
                    if ($child instanceof \DOMElement) {
803 1
                        $newnode = $child;
804 1
                        $elementFound = true;
805 1
                        break;
806
                    }
807 1
                }
808 1
                if (!$elementFound) {
809 1
                    break;
810
                }
811 1
            }
812 1
            $newnode->appendChild($oldnode);
813 1
            $newnodes[] = $newnode;
814 1
        }
815 1
        $content->clear();
816 1
        $content->add($newnodes);
817 1
        return $this;
818
    }
819
820
    /**
821
     * Wrap an HTML structure around all elements in the set of matched elements.
822
     *
823
     * @param string|HtmlPageCrawler|\DOMNode|\DOMNodeList $content
824
     * @throws \LogicException
825
     * @return \Wa72\HtmlPageDom\HtmlPageCrawler $this for chaining
826
     * @api
827
     */
828 1
    public function wrapAll($content)
829
    {
830 1
        $content = self::create($content);
831 1
        $parent = $this->getNode(0)->parentNode;
832 1
        foreach ($this as $i => $node) {
833
            /** @var \DOMNode $node */
834 1
            if ($node->parentNode !== $parent) {
835
                throw new \LogicException('Nodes to be wrapped with wrapAll() must all have the same parent');
836
            }
837 1
        }
838
839 1
        $newnode = $content->getNode(0);
840
        /** @var \DOMNode $newnode */
841 1
        $newnode = static::importNewnode($newnode, $parent);
842
843 1
        $newnode = $parent->insertBefore($newnode,$this->getNode(0));
844 1
        $content->clear();
845 1
        $content->add($newnode);
846
847 1
        while ($newnode->hasChildNodes()) {
848 1
            $elementFound = false;
849 1
            foreach ($newnode->childNodes as $child) {
850 1
                if ($child instanceof \DOMElement) {
851 1
                    $newnode = $child;
852 1
                    $elementFound = true;
853 1
                    break;
854
                }
855 1
            }
856 1
            if (!$elementFound) {
857
                break;
858
            }
859 1
        }
860 1
        foreach ($this as $i => $node) {
861
            /** @var \DOMNode $node */
862 1
            $newnode->appendChild($node);
863 1
        }
864 1
        return $this;
865
    }
866
867
    /**
868
     * Wrap an HTML structure around the content of each element in the set of matched elements.
869
     *
870
     * @param string|HtmlPageCrawler|\DOMNode|\DOMNodeList $content
871
     * @return \Wa72\HtmlPageDom\HtmlPageCrawler $this for chaining
872
     * @api
873
     */
874 1
    public function wrapInner($content)
875
    {
876 1
        foreach ($this as $i => $node) {
877
            /** @var \DOMNode $node */
878 1
            self::create($node->childNodes)->wrapAll($content);
879 1
        }
880 1
        return $this;
881
    }
882
883
    /**
884
     * Get the HTML code fragment of all elements and their contents.
885
     *
886
     * If the first node contains a complete HTML document return only
887
     * the full code of this document.
888
     *
889
     * @return string HTML code (fragment)
890
     * @api
891
     */
892 8
    public function saveHTML()
893
    {
894 8
        if ($this->isHtmlDocument()) {
895 1
            return $this->getDOMDocument()->saveHTML();
896
        } else {
897 8
            $doc = new \DOMDocument('1.0', 'UTF-8');
898 8
            $root = $doc->appendChild($doc->createElement('_root'));
899 8
            foreach ($this as $node) {
900 8
                $root->appendChild($doc->importNode($node, true));
901 8
            }
902 8
            $html = trim($doc->saveHTML());
903 8
            return preg_replace('@^<'.self::FRAGMENT_ROOT_TAGNAME.'[^>]*>|</'.self::FRAGMENT_ROOT_TAGNAME.'>$@', '', $html);
904
        }
905
    }
906
907 4
    public function __toString()
908
    {
909 4
        return $this->saveHTML();
910
    }
911
912
    /**
913
     * checks whether the first node contains a complete html document
914
     * (as opposed to a document fragment)
915
     *
916
     * @return boolean
917
     */
918 8
    public function isHtmlDocument()
919
    {
920 8
        $node = $this->getNode(0);
921
        if ($node instanceof \DOMElement
922 8
            && $node->ownerDocument instanceof \DOMDocument
923 8
            && $node->ownerDocument->documentElement === $node
924 8
            && $node->nodeName == 'html'
925 8
        ) {
926 1
            return true;
927
        } else {
928 8
            return false;
929
        }
930
    }
931
932
    /**
933
     * get ownerDocument of the first element
934
     *
935
     * @return \DOMDocument|null
936
     */
937 1
    public function getDOMDocument()
938
    {
939 1
        $node = $this->getNode(0);
940 1
        $r = null;
941
        if ($node instanceof \DOMElement
942 1
            && $node->ownerDocument instanceof \DOMDocument
943 1
        ) {
944 1
            $r = $node->ownerDocument;
945 1
        }
946 1
        return $r;
947
    }
948
949
    /**
950
     * Filters the list of nodes with a CSS selector.
951
     *
952
     * @param string $selector
953
     * @return HtmlPageCrawler
954
     */
955 8
    public function filter($selector)
956
    {
957 8
        return parent::filter($selector);
958
    }
959
960
    /**
961
     * Filters the list of nodes with an XPath expression.
962
     *
963
     * @param string $xpath An XPath expression
964
     *
965
     * @return HtmlPageCrawler A new instance of Crawler with the filtered list of nodes
966
     *
967
     * @api
968
     */
969 2
    public function filterXPath($xpath)
970
    {
971 2
        return parent::filterXPath($xpath);
972
    }
973
974
    /**
975
     * Adds HTML/XML content to the HtmlPageCrawler object (but not to the DOM of an already attached node).
976
     *
977
     * Function overriden from Crawler because HTML fragments are always added as complete documents there
978
     *
979
     *
980
     * @param string      $content A string to parse as HTML/XML
981
     * @param null|string $type    The content type of the string
982
     *
983
     * @return null|void
984
     */
985 17
    public function addContent($content, $type = null)
986
    {
987 17
        if (empty($type)) {
988 17
            $type = 'text/html;charset=UTF-8';
989 17
        }
990 17
        if (substr($type, 0, 9) == 'text/html' && !preg_match('/<html\b[^>]*>/i', $content)) {
991
            // string contains no <html> Tag => no complete document but an HTML fragment!
992 16
            $this->addHtmlFragment($content);
993 16
        } else {
994 2
            parent::addContent($content, $type);
995
        }
996 17
    }
997
998 15
    public function addHtmlFragment($content, $charset = 'UTF-8')
999
    {
1000 15
        $d = new \DOMDocument('1.0', $charset);
1001 15
        $root = $d->appendChild($d->createElement(self::FRAGMENT_ROOT_TAGNAME));
1002 15
        $bodynode = Helpers::getBodyNodeFromHtmlFragment($content, $charset);
1003 15
        foreach ($bodynode->childNodes as $child) {
1004 15
            $inode = $root->appendChild($d->importNode($child, true));
1005 15
            if ($inode) {
1006 15
                $this->addNode($inode);
1007 15
            }
1008 15
        }
1009 15
    }
1010
1011
    /**
1012
     * returns the first node
1013
     * deprecated, use getNode(0) instead
1014
     *
1015
     * @return \DOMNode|null
1016
     * @deprecated
1017
     * @see Crawler::getNode
1018
     */
1019
    public function getFirstNode()
1020
    {
1021
        return $this->getNode(0);
1022
    }
1023
1024
    /**
1025
     * @param int $position
1026
     *
1027
     * overridden from Crawler because it is not public in Symfony 2.3
1028
     * TODO: throw away as soon as we don't need to support SF 2.3 any more
1029
     *
1030
     * @return \DOMElement|null
1031
     */
1032 14
    public function getNode($position)
1033
    {
1034 14
        return parent::getNode($position);
1035
    }
1036
1037
    /**
1038
     * Returns the node name of the first node of the list.
1039
     *
1040
     * in Crawler (parent), this function will be available starting with 2.6.0,
1041
     * therefore this method be removed from here as soon as we don't need to keep compatibility
1042
     * with Symfony < 2.6
1043
     *
1044
     * TODO: throw away as soon as we don't need to support SF 2.3 any more
1045
     *
1046
     * @return string The node name
1047
     *
1048
     * @throws \InvalidArgumentException When current node is empty
1049
     */
1050 1
    public function nodeName()
1051
    {
1052 1
        if (!count($this)) {
1053
            throw new \InvalidArgumentException('The current node list is empty.');
1054
        }
1055 1
        return $this->getNode(0)->nodeName;
1056
    }
1057
1058
    /**
1059
     * Adds a node to the current list of nodes.
1060
     *
1061
     * This method uses the appropriate specialized add*() method based
1062
     * on the type of the argument.
1063
     *
1064
     * Overwritten from parent to allow Crawler to be added
1065
     *
1066
     * @param null|\DOMNodeList|array|\DOMNode|Crawler $node A node
1067
     *
1068
     * @api
1069
     */
1070 29
    public function add($node)
1071
    {
1072 29
        if ($node instanceof Crawler) {
1073 1
            foreach ($node as $childnode) {
1074 1
                $this->addNode($childnode);
1075 1
            }
1076 1
        } else {
1077 29
            parent::add($node);
1078
        }
1079 29
    }
1080
1081
    /**
1082
     * @param \DOMNode $newnode
1083
     * @param \DOMNode $referencenode
1084
     * @param int $clone
1085
     * @return \DOMNode
1086
     */
1087 6
    protected static function importNewnode(\DOMNode $newnode, \DOMNode $referencenode, $clone = 0) {
1088 6
        if ($newnode->ownerDocument !== $referencenode->ownerDocument) {
1089 5
            $newnode = $referencenode->ownerDocument->importNode($newnode, true);
1090 5
        } else {
1091 2
            if ($clone > 0) {
1092
                $newnode = $newnode->cloneNode(true);
1093
            }
1094
        }
1095 6
        return $newnode;
1096
    }
1097
1098
    /**
1099
     * Checks whether the first node in the set is disconnected (has no parent node)
1100
     *
1101
     * @return bool
1102
     */
1103 1
    public function isDisconnected()
1104
    {
1105 1
        $parent = $this->getNode(0)->parentNode;
1106 1
        return ($parent == null || $parent->tagName == self::FRAGMENT_ROOT_TAGNAME);
1107
    }
1108
1109 1
    public function __get($name)
1110
    {
1111
        switch ($name) {
1112 1
            case 'count':
1113 1
            case 'length':
1114 1
                return count($this);
1115
        }
1116 1
        throw new \Exception('No such property ' . $name);
1117
    }
1118
}
1119