Completed
Push — master ( 9e3cb6...9c9a79 )
by Ivan
05:34
created

Html   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 2

Test Coverage

Coverage 100%

Importance

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

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A resolveLinkAttribute() 0 14 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 1
        $this->document = new DOMDocument();
34 1
        $this->document->loadHtml($html);
35 1
        $this->xpath = new DOMXPath($this->document);
36 1
    }
37
38
    /**
39
     * @param  string       $attribute
40
     * @param  UriInterface $base
41
     */
42 1
    private function resolveLinkAttribute($attribute, UriInterface $base)
43
    {
44 1
        $elements = $this->xpath->query(
45 1
            "//*[@$attribute and not(contains(@$attribute, \"://\"))]"
46 1
        );
47
48 1
        foreach ($elements as $element) {
49
            try {
50 1
                $resolved = Uri::resolve($base, $element->getAttribute($attribute));
51 1
                $element->setAttribute($attribute, $resolved->__toString());
52 1
            } catch (InvalidArgumentException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
53
            }
54 1
        }
55 1
    }
56
57
    /**
58
     * Add a prefix to all relative links (src, href and action)
59
     *
60
     * @param  UriInterface $base
61
     */
62 1
    public function resolveLinks(UriInterface $base)
63
    {
64 1
        $this->resolveLinkAttribute('href', $base);
65 1
        $this->resolveLinkAttribute('src', $base);
66 1
        $this->resolveLinkAttribute('action', $base);
67
68 1
        return $this;
69
    }
70
71
    /**
72
     * @return string
73
     */
74 1
    public function get()
75
    {
76 1
        return $this->document->saveHtml();
77
    }
78
}
79