Html   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 64
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 2

Test Coverage

Coverage 22.73%

Importance

Changes 2
Bugs 0 Features 1
Metric Value
wmc 6
c 2
b 0
f 1
lcom 2
cbo 2
dl 0
loc 64
ccs 5
cts 22
cp 0.2273
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A resolveLinkAttribute() 0 15 3
A resolveLinks() 0 8 1
A get() 0 4 1
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