simplesamlphp /
xml-common
| 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
Bug
introduced
by
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 | /** |
||
| 50 | * Do an XPath query on an XML node. |
||
| 51 | * |
||
| 52 | * @param \DOMNode $node The XML node. |
||
| 53 | * @param string $query The query. |
||
| 54 | * @param \DOMXPath $xpCache The DOMXPath object |
||
| 55 | * @return array<\DOMNode> Array with matching DOM nodes. |
||
| 56 | */ |
||
| 57 | public static function xpQuery(DOMNode $node, string $query, DOMXPath $xpCache): array |
||
| 58 | { |
||
| 59 | $ret = []; |
||
| 60 | |||
| 61 | $results = $xpCache->query($query, $node); |
||
| 62 | Assert::notFalse($results, 'Malformed XPath query or invalid contextNode provided.'); |
||
| 63 | |||
| 64 | for ($i = 0; $i < $results->length; $i++) { |
||
| 65 | $ret[$i] = $results->item($i); |
||
| 66 | } |
||
| 67 | |||
| 68 | return $ret; |
||
| 69 | } |
||
| 70 | } |
||
| 71 |