Passed
Branch scrutinizer (a800ff)
by Thomas
02:24
created

HtmlDocument::find()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 3
eloc 7
c 1
b 1
f 0
nc 3
nop 1
dl 0
loc 12
rs 10
1
<?php
2
3
namespace Sulao\HtmlQuery;
4
5
use DOMDocument, DOMNode;
6
7
/**
8
 * Class HtmlDocument
9
 *
10
 * @package Sulao\HtmlQuery
11
 */
12
class HtmlDocument
13
{
14
    /**
15
     * @var DOMDocument
16
     */
17
    protected $doc;
18
19
    /**
20
     * HtmlDocument constructor.
21
     *
22
     * @param DOMDocument $doc
23
     */
24
    public function __construct(DOMDocument $doc)
25
    {
26
        $this->doc = $doc;
27
    }
28
29
    /**
30
     * Get DOMDocument
31
     *
32
     * @return DOMDocument
33
     */
34
    public function getDoc(): DOMDocument
35
    {
36
        return $this->doc;
37
    }
38
39
    /**
40
     * Get the outer HTML content.
41
     *
42
     * @return string|null
43
     */
44
    public function outerHtml()
45
    {
46
        return $this->doc->saveHTML();
47
    }
48
49
    /**
50
     *  Make the static object can be called as a function.
51
     *
52
     * @param string $selector
53
     *
54
     * @return HtmlQuery
55
     */
56
    public function __invoke(string $selector)
57
    {
58
        return $this->query($selector);
59
    }
60
61
    /**
62
     * If the parameter is raw html, then create document fragment for it,
63
     * If the parameter is a css selector, get the descendants
64
     * filtered by a css selector.
65
     *
66
     * @param string $selector css selector or raw html
67
     *
68
     * @return HtmlQuery
69
     */
70
    public function query(string $selector)
71
    {
72
        if (Helper::isRawHtml($selector)) {
73
            $frag = $this->doc->createDocumentFragment();
74
            $frag->appendXML($selector);
75
76
            return $this->resolve($frag);
77
        }
78
79
        return $this->find($selector);
80
    }
81
82
    /**
83
     * Get the descendants of document, filtered by a selector.
84
     *
85
     * @param string $selector
86
     *
87
     * @return HtmlQuery
88
     */
89
    public function find(string $selector)
90
    {
91
        $nodes = Helper::xpathQuery(
92
            Helper::toXpath($selector),
93
            $this->doc,
94
            $this->doc
95
        );
96
        if (Helper::isIdSelector($selector)) {
97
            $nodes = $nodes ? $nodes[0] : [];
98
        }
99
100
        return $this->resolve($nodes);
101
    }
102
103
    /**
104
     * Resolve nodes to HtmlQuery instance.
105
     *
106
     * @param DOMNode|DOMNode[] $nodes
107
     *
108
     * @return HtmlQuery
109
     */
110
    protected function resolve($nodes)
111
    {
112
        return new HtmlQuery($this->doc, $nodes);
113
    }
114
}
115