Lines 79.16% 19 / 24
Methods 0.00% 0 / 2
Classes 0.00% 0 / 1
Name Lines Methods CRAP
 findNodes 92.30% 12 / 13 0.00% 0 / 1 6.02
 getAttribute 63.63% 7 / 11 0.00% 0 / 1 7.73
14class HtmlFinder
15{
16    /**
17     * @return DOMNode[]
18     */
19    public function findNodes(string $html, string $xpath): array
20    {
21        $document = new DOMDocument();
22        try {
23            if (!$document->loadHTML($html, LIBXML_NOWARNING | LIBXML_NOERROR)) {
24                throw new InvalidHtmlException();
25            }
26        } catch (ValueError) {
27            throw new InvalidHtmlException();
28        }
29        $nodes = new DOMXPath($document)->query($xpath);
30        if ($nodes === false) {
31            throw new InvalidQueryException();
32        }
33        $domNodes = [];
34        foreach ($nodes as $node) {
35            if ($node instanceof DOMNode) {
36                $domNodes[] = $node;
37            }
38        }
39        return $domNodes;
40    }
41
42    public function getAttribute(DOMNode $node, string $attribute): string
43    {
44        if ($node->attributes === null) {
45            throw new InvalidHtmlException();
46        }
47        for ($i = 0; $i < $node->attributes->length; $i++) {
48            $attributeNode = $node->attributes->item($i);
49            if ($attributeNode === null) {
50                throw new InvalidHtmlException();
51            }
52            if ($attributeNode->nodeName === $attribute) {
53                if ($attributeNode->nodeValue === null) {
54                    continue;
55                }
56                return $attributeNode->nodeValue;
57            }
58        }
59
60        throw new InvalidHtmlException();
61    }
62}