Completed
Push — master ( 7c3f70...4ee5e3 )
by Tim
16s queued 13s
created

XPath::getXPath()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 9
c 1
b 0
f 0
nc 4
nop 1
dl 0
loc 17
rs 9.9666
1
<?php
2
3
declare(strict_types=1);
4
5
namespace SimpleSAML\XML\Utils;
6
7
use DOMDocument;
8
use DOMElement;
9
use DOMNode;
10
use DOMXPath;
11
use InvalidArgumentException;
12
use SimpleSAML\Assert\Assert;
13
14
/**
15
 * XPath helper functions for the XML library.
16
 *
17
 * @package simplesamlphp/xml-common
18
 */
19
class XPath
20
{
21
    /**
22
     * Get an instance of DOMXPath associated with a DOMNode
23
     *
24
     * @param \DOMNode $node The associated node
25
     * @return \DOMXPath
26
     */
27
    public static function getXPath(DOMNode $node): DOMXPath
28
    {
29
        static $xpCache = null;
30
31
        if ($node instanceof DOMDocument) {
32
            $doc = $node;
33
        } else {
34
            $doc = $node->ownerDocument;
35
            Assert::notNull($doc);
36
            /** @psalm-var \DOMDocument $doc */
37
        }
38
39
        if ($xpCache === null || !$xpCache->document->isSameNode($doc)) {
40
            $xpCache = new DOMXPath($doc);
0 ignored issues
show
Bug introduced by
It seems like $doc can also be of type null; however, parameter $document of DOMXPath::__construct() does only seem to accept DOMDocument, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

40
            $xpCache = new DOMXPath(/** @scrutinizer ignore-type */ $doc);
Loading history...
41
        }
42
43
        return $xpCache;
44
    }
45
46
    /**
47
     * Do an XPath query on an XML node.
48
     *
49
     * @param \DOMNode $node  The XML node.
50
     * @param string $query The query.
51
     * @param \DOMXPath|null $xpCache The DOMXPath object or NULL to create one
52
     * @return \DOMNode[] Array with matching DOM nodes.
53
     */
54
    public static function xpQuery(DOMNode $node, string $query, DOMXPath $xpCache): array
55
    {
56
        $ret = [];
57
58
        $results = $xpCache->query($query, $node);
59
        for ($i = 0; $i < $results->length; $i++) {
60
            $ret[$i] = $results->item($i);
61
        }
62
63
        return $ret;
64
    }
65
}
66