Issues (21)

src/Utils/XPath.php (2 issues)

1
<?php
2
3
declare(strict_types=1);
4
5
namespace SimpleSAML\XML\Utils;
6
7
use DOMDocument;
8
use DOMNode;
9
use DOMXPath;
10
use SimpleSAML\Assert\Assert;
11
12
/**
13
 * XPath helper functions for the XML library.
14
 *
15
 * @package simplesamlphp/xml-common
16
 */
17
class XPath
18
{
19
    /**
20
     * Get an instance of DOMXPath associated with a DOMNode
21
     *
22
     * @param \DOMNode $node The associated node
23
     * @return \DOMXPath
24
     */
25
    public static function getXPath(DOMNode $node): DOMXPath
26
    {
27
        static $xpCache = null;
28
29
        if ($node instanceof DOMDocument) {
30
            $doc = $node;
31
        } else {
32
            $doc = $node->ownerDocument;
33
            Assert::notNull($doc);
34
        }
35
36
        if ($xpCache === null || !$xpCache->document->isSameNode($doc)) {
37
            $xpCache = new DOMXPath($doc);
0 ignored issues
show
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

37
            $xpCache = new DOMXPath(/** @scrutinizer ignore-type */ $doc);
Loading history...
38
        }
39
40
        return $xpCache;
41
    }
42
43
    /**
44
     * Do an XPath query on an XML node.
45
     *
46
     * @param \DOMNode $node  The XML node.
47
     * @param string $query The query.
48
     * @param \DOMXPath $xpCache The DOMXPath object
49
     * @return array<int<0, max>, \DOMNameSpaceNode|\DOMNode|null> Array with matching DOM nodes.
0 ignored issues
show
Documentation Bug introduced by
The doc comment array<int<0, max>, \DOMN...paceNode|\DOMNode|null> at position 2 could not be parsed: Expected '>' at position 2, but found 'int'.
Loading history...
50
     */
51
    public static function xpQuery(DOMNode $node, string $query, DOMXPath $xpCache): array
52
    {
53
        $ret = [];
54
55
        $results = $xpCache->query($query, $node);
56
        for ($i = 0; $i < $results->length; $i++) {
57
            $ret[$i] = $results->item($i);
58
        }
59
60
        return $ret;
61
    }
62
}
63