XPath   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 10
c 2
b 0
f 0
dl 0
loc 39
rs 10
wmc 4

2 Methods

Rating   Name   Duplication   Size   Complexity  
A findElement() 0 10 3
A getXPath() 0 6 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace SimpleSAML\XMLSecurity\Utils;
6
7
use DOMDocument;
8
use DOMElement;
9
use DOMNode;
10
use DOMXPath;
11
use SimpleSAML\XML\Utils\XPath as XPathUtils;
12
use SimpleSAML\XMLSecurity\Constants as C;
13
use SimpleSAML\XMLSecurity\Exception\RuntimeException;
14
15
/**
16
 * Compilation of utilities for XPath.
17
 *
18
 * @package simplesamlphp/xml-security
19
 */
20
class XPath extends XPathUtils
21
{
22
    /**
23
     * Get a DOMXPath object that can be used to search for XMLDSIG elements.
24
     *
25
     * @param \DOMNode $node The document to associate to the DOMXPath object.
26
     *
27
     * @return \DOMXPath A DOMXPath object ready to use in the given document, with the XMLDSIG namespace already
28
     * registered.
29
     */
30
    public static function getXPath(DOMNode $node): DOMXPath
31
    {
32
        $xp = parent::getXPath($node);
33
        $xp->registerNamespace('ds', C::NS_XDSIG);
34
        $xp->registerNamespace('xenc', C::NS_XENC);
35
        return $xp;
36
    }
37
38
39
    /**
40
     * Search for an element with a certain name among the children of a reference element.
41
     *
42
     * @param \DOMNode $ref The DOMDocument or DOMElement where encrypted data is expected to be found as a child.
43
     * @param string $name The name (possibly prefixed) of the element we are looking for.
44
     *
45
     * @return \DOMElement|false The element we are looking for, or false when not found.
46
     *
47
     * @throws RuntimeException If no DOM document is available.
48
     */
49
    public static function findElement(DOMNode $ref, string $name): DOMElement|false
50
    {
51
        $doc = $ref instanceof DOMDocument ? $ref : $ref->ownerDocument;
52
        if ($doc === null) {
53
            throw new RuntimeException('Cannot search, no DOM document available');
54
        }
55
56
        $nodeset = self::getXPath($doc)->query('./' . $name, $ref);
57
58
        return $nodeset->item(0) ?? false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $nodeset->item(0) ?? false could return the type DOMNode which includes types incompatible with the type-hinted return DOMElement|false. Consider adding an additional type-check to rule them out.
Loading history...
59
    }
60
}
61