1<?php declare(strict_types=1);
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    /** @var string[] */
11    protected $errors = [];
12    /** @var string */
13    protected $entityId = '';
14
15    /**
16     * @param string $xml
17     */
18    public function parse(string $xml) : void
19    {
20        libxml_use_internal_errors(true);
21
22        $xml = new SimpleXMLElement($xml);
23
24        $xml->registerXPathNamespace('md', 'urn:oasis:names:tc:SAML:2.0:metadata');
25        $xml->registerXPathNamespace('mdui', 'urn:oasis:names:tc:SAML:metadata:ui');
26
27        $idps = $xml->xpath('//md:EntityDescriptor[//md:IDPSSODescriptor]');
28        $entityid = null;
29        if ($idps && isset($idps[0])) {
30            $entityid = (string) $idps[0]->attributes('', true)->entityID[0];
31        }
32
33        foreach (libxml_get_errors() as $error) {
34            $this->pushError($error->line . ': ' . $error->message);
35        }
36
37        if ($entityid) {
38            $this->entityId = $entityid;
39        }
40
41        libxml_clear_errors();
42    }
43
44    /**
45     * @param string $error
46     */
47    private function pushError(string $error) : void
48    {
49        $this->errors[] = $error;
50    }
51
52    /**
53     * @return bool
54     */
55    public function hasErrors() : bool
56    {
57        return count($this->getErrors()) > 0;
58    }
59
60    /**
61     * @return string[]
62     */
63    public function getErrors() : array
64    {
65        return $this->errors;
66    }
67
68    /**
69     * @return string
70     */
71    public function getEntityId() : string
72    {
73        return $this->entityId;
74    }
75}
76