Issues (33)

src/XPath/XPath.php (2 issues)

1
<?php
2
3
declare(strict_types=1);
4
5
namespace SimpleSAML\XPath;
6
7
use DOMDocument;
8
use DOMNode;
9
use DOMXPath;
10
use SimpleSAML\XML\Assert\Assert;
11
use SimpleSAML\XML\Constants as C_XML;
12
use SimpleSAML\XMLSchema\Constants as C_XS;
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
        }
37
38
        if ($xpCache === null || !$xpCache->document->isSameNode($doc)) {
39
            $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

39
            $xpCache = new DOMXPath(/** @scrutinizer ignore-type */ $doc);
Loading history...
40
        }
41
42
        $xpCache->registerNamespace('xml', C_XML::NS_XML);
43
        $xpCache->registerNamespace('xs', C_XS::NS_XS);
44
45
        return $xpCache;
46
    }
47
48
    /**
49
     * Do an XPath query on an XML node.
50
     *
51
     * @param \DOMNode $node  The XML node.
52
     * @param string $query The query.
53
     * @param \DOMXPath $xpCache The DOMXPath object
54
     * @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...
55
     */
56
    public static function xpQuery(DOMNode $node, string $query, DOMXPath $xpCache): array
57
    {
58
        $ret = [];
59
60
        $results = $xpCache->query($query, $node);
61
        for ($i = 0; $i < $results->length; $i++) {
62
            $ret[$i] = $results->item($i);
63
        }
64
65
        return $ret;
66
    }
67
}
68