Html::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1.216

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 6
ccs 2
cts 5
cp 0.4
rs 9.4285
cc 1
eloc 4
nc 1
nop 1
crap 1.216
1
<?php
2
3
namespace SP\Spiderling;
4
5
use GuzzleHttp\Psr7\Uri;
6
use Psr\Http\Message\UriInterface;
7
use DOMDocument;
8
use DOMXPath;
9
use InvalidArgumentException;
10
11
/**
12
 * @author    Ivan Kerin <[email protected]>
13
 * @copyright 2015, Clippings Ltd.
14
 * @license   http://spdx.org/licenses/BSD-3-Clause
15
 */
16
class Html
17
{
18
    /**
19
     * @var DOMDocument
20
     */
21
    private $document;
22
23
    /**
24
     * @var DOMXPath
25
     */
26
    private $xpath;
27
28
    /**
29
     * @param string $html
30
     */
31 1
    public function __construct($html)
32
    {
33
        $this->document = new DOMDocument();
34
        $this->document->loadHtml($html);
35
        $this->xpath = new DOMXPath($this->document);
36 1
    }
37
38
    /**
39
     * @param  string       $attribute
40
     * @param  UriInterface $base
41
     */
42
    private function resolveLinkAttribute($attribute, UriInterface $base)
43
    {
44
        $elements = $this->xpath->query(
45
            "//*[@$attribute and not(contains(@$attribute, \"://\"))]"
46
        );
47
48
        foreach ($elements as $element) {
49
            try {
50
                $resolved = Uri::resolve($base, $element->getAttribute($attribute));
51
                $element->setAttribute($attribute, $resolved->__toString());
52
            } catch (InvalidArgumentException $e) {
53
                // Tolerate invalid urls
54
            }
55
        }
56
    }
57
58
    /**
59
     * Add a prefix to all relative links (src, href and action)
60
     *
61
     * @param  UriInterface $base
62
     */
63 1
    public function resolveLinks(UriInterface $base)
64
    {
65
        $this->resolveLinkAttribute('href', $base);
66
        $this->resolveLinkAttribute('src', $base);
67
        $this->resolveLinkAttribute('action', $base);
68
69 1
        return $this;
70 1
    }
71
72
    /**
73
     * @return string
74
     */
75
    public function get()
76
    {
77
        return $this->document->saveHtml();
78
    }
79
}
80