File: Parser.php

package info (click to toggle)
simplesamlphp 1.16.3-1%2Bdeb10u2
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 21,036 kB
  • sloc: php: 73,175; ansic: 875; sh: 83; perl: 82; xml: 52; makefile: 46
file content (77 lines) | stat: -rw-r--r-- 2,316 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
<?php

/**
 * This file will help doing XPath queries in SAML 2 XML documents.
 *
 * @author Andreas Åkre Solberg, UNINETT AS. <andreas.solberg@uninett.no>
 * @package SimpleSAMLphp
 */

namespace SimpleSAML\XML;

class Parser
{
    public $simplexml = null;

    public function __construct($xml)
    {
        ;
        $this->simplexml = new \SimpleXMLElement($xml);
        $this->simplexml->registerXPathNamespace('saml2', 'urn:oasis:names:tc:SAML:2.0:assertion');
        $this->simplexml->registerXPathNamespace('saml2meta', 'urn:oasis:names:tc:SAML:2.0:metadata');
        $this->simplexml->registerXPathNamespace('ds', 'http://www.w3.org/2000/09/xmldsig#');
    }
    
    public static function fromSimpleXMLElement(\SimpleXMLElement $element)
    {
        
        // Traverse all existing namespaces in element
        $namespaces = $element->getNamespaces();
        foreach ($namespaces as $prefix => $ns) {
            $element[(($prefix === '') ? 'xmlns' : 'xmlns:' . $prefix)] = $ns;
        }
        
        /* Create a new parser with the xml document where the namespace definitions
         * are added.
         */
        $parser = new Parser($element->asXML());
        return $parser;
    }
    
    public function getValueDefault($xpath, $defvalue)
    {
        try {
            return $this->getValue($xpath, true);
        } catch (\Exception $e) {
            return $defvalue;
        }
    }
    
    public function getValue($xpath, $required = false)
    {
        $result = $this->simplexml->xpath($xpath);
        if (!is_array($result) || empty($result)) {
            if ($required) {
                throw new \Exception('Could not get value from XML document using the following XPath expression: ' . $xpath);
            } else {
                return null;
            }
        }
        return (string) $result[0];
    }
    
    public function getValueAlternatives(array $xpath, $required = false)
    {
        foreach ($xpath as $x) {
            $seek = $this->getValue($x);
            if ($seek) {
                return $seek;
            }
        }
        if ($required) {
            throw new \Exception('Could not get value from XML document using multiple alternative XPath expressions.');
        } else {
            return null;
        }
    }
}