1<?php
2/* Copyright (c) 1998-2017 ILIAS open source, Extended GPL, see docs/LICENSE */
3
4/**
5 * Class ilSamlIdpXmlMetadataParser
6 * @author Michael Jansen <mjansen@databay.de>
7 */
8class ilSamlIdpXmlMetadataParser
9{
10    /**
11     * @var string[]
12     */
13    protected $errors = [];
14
15    /**
16     * @var string
17     */
18    protected $entityId = '';
19
20    /**
21     * @param string $xml
22     */
23    public function parse($xml)
24    {
25        \libxml_use_internal_errors(true);
26
27        $xml = new \SimpleXMLElement($xml);
28
29        $xml->registerXPathNamespace('md', 'urn:oasis:names:tc:SAML:2.0:metadata');
30        $xml->registerXPathNamespace('mdui', 'urn:oasis:names:tc:SAML:metadata:ui');
31
32        $idps = $xml->xpath('//md:EntityDescriptor[//md:IDPSSODescriptor]');
33        $entityid = null;
34        if ($idps && isset($idps[0])) {
35            $entityid = (string) $idps[0]->attributes('', true)->entityID[0];
36        }
37
38        foreach (\libxml_get_errors() as $error) {
39            $this->pushError($error->line . ': ' . $error->message);
40        }
41
42        if ($entityid) {
43            $this->entityId = $entityid;
44        }
45
46        \libxml_clear_errors();
47    }
48
49    /**
50     * @param string $error
51     */
52    private function pushError($error)
53    {
54        $this->errors[] = $error;
55    }
56
57    /**
58     * @return bool
59     */
60    public function hasErrors()
61    {
62        return count($this->getErrors()) > 0;
63    }
64
65    /**
66     * @return string[]
67     */
68    public function getErrors()
69    {
70        return $this->errors;
71    }
72
73    /**
74     * @return string
75     */
76    public function getEntityId()
77    {
78        return $this->entityId;
79    }
80}
81