aboutsummaryrefslogtreecommitdiffstats
path: root/vendor/sabre/xml/lib/Reader.php
blob: 7cba76c595cf31ae4ab535999b0ffd4114b17f9a (plain) (blame)
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
<?php

namespace Sabre\Xml;

use XMLReader;

/**
 * The Reader class expands upon PHP's built-in XMLReader.
 *
 * The intended usage, is to assign certain XML elements to PHP classes. These
 * need to be registered using the $elementMap public property.
 *
 * After this is done, a single call to parse() will parse the entire document,
 * and delegate sub-sections of the document to element classes.
 *
 * @copyright Copyright (C) 2009-2015 fruux GmbH (https://fruux.com/).
 * @author Evert Pot (http://evertpot.com/)
 * @license http://sabre.io/license/ Modified BSD License
 */
class Reader extends XMLReader {

    use ContextStackTrait;

    /**
     * Returns the current nodename in clark-notation.
     *
     * For example: "{http://www.w3.org/2005/Atom}feed".
     * Or if no namespace is defined: "{}feed".
     *
     * This method returns null if we're not currently on an element.
     *
     * @return string|null
     */
    function getClark() {

        if (! $this->localName) {
            return null;
        }

        return '{' . $this->namespaceURI . '}' . $this->localName;

    }

    /**
     * Reads the entire document.
     *
     * This function returns an array with the following three elements:
     *    * name - The root element name.
     *    * value - The value for the root element.
     *    * attributes - An array of attributes.
     *
     * This function will also disable the standard libxml error handler (which
     * usually just results in PHP errors), and throw exceptions instead.
     *
     * @return array
     */
    function parse() {

        $previousEntityState = libxml_disable_entity_loader(true);
        $previousSetting = libxml_use_internal_errors(true);

        // Really sorry about the silence operator, seems like I have no
        // choice. See:
        //
        // https://bugs.php.net/bug.php?id=64230
        while ($this->nodeType !== self::ELEMENT && @$this->read()) {
            // noop
        }
        $result = $this->parseCurrentElement();

        $errors = libxml_get_errors();
        libxml_clear_errors();
        libxml_use_internal_errors($previousSetting);
        libxml_disable_entity_loader($previousEntityState);

        if ($errors) {
            throw new LibXMLException($errors);
        }

        return $result;
    }



    /**
     * parseGetElements parses everything in the current sub-tree,
     * and returns a an array of elements.
     *
     * Each element has a 'name', 'value' and 'attributes' key.
     *
     * If the the element didn't contain sub-elements, an empty array is always
     * returned. If there was any text inside the element, it will be
     * discarded.
     *
     * If the $elementMap argument is specified, the existing elementMap will
     * be overridden while parsing the tree, and restored after this process.
     *
     * @param array $elementMap
     * @return array
     */
    function parseGetElements(array $elementMap = null) {

        $result = $this->parseInnerTree($elementMap);
        if (!is_array($result)) {
            return [];
        }
        return $result;

    }

    /**
     * Parses all elements below the current element.
     *
     * This method will return a string if this was a text-node, or an array if
     * there were sub-elements.
     *
     * If there's both text and sub-elements, the text will be discarded.
     *
     * If the $elementMap argument is specified, the existing elementMap will
     * be overridden while parsing the tree, and restored after this process.
     *
     * @param array $elementMap
     * @return array|string
     */
    function parseInnerTree(array $elementMap = null) {

        $text = null;
        $elements = [];

        if ($this->nodeType === self::ELEMENT && $this->isEmptyElement) {
            // Easy!
            $this->next();
            return null;
        }

        if (!is_null($elementMap)) {
            $this->pushContext();
            $this->elementMap = $elementMap;
        }

        // Really sorry about the silence operator, seems like I have no
        // choice. See:
        //
        // https://bugs.php.net/bug.php?id=64230
        if (!@$this->read()) return false;

        while (true) {

            if (!$this->isValid()) {

                $errors = libxml_get_errors();

                if ($errors) {
                    libxml_clear_errors();
                    throw new LibXMLException($errors);
                }
            }

            switch ($this->nodeType) {
                case self::ELEMENT :
                    $elements[] = $this->parseCurrentElement();
                    break;
                case self::TEXT :
                case self::CDATA :
                    $text .= $this->value;
                    $this->read();
                    break;
                case self::END_ELEMENT :
                    // Ensuring we are moving the cursor after the end element.
                    $this->read();
                    break 2;
                case self::NONE :
                    throw new ParseException('We hit the end of the document prematurely. This likely means that some parser "eats" too many elements. Do not attempt to continue parsing.');
                default :
                    // Advance to the next element
                    $this->read();
                    break;
            }

        }

        if (!is_null($elementMap)) {
            $this->popContext();
        }
        return ($elements ? $elements : $text);

    }

    /**
     * Reads all text below the current element, and returns this as a string.
     *
     * @return string
     */
    function readText() {

        $result = '';
        $previousDepth = $this->depth;

        while ($this->read() && $this->depth != $previousDepth) {
            if (in_array($this->nodeType, [XMLReader::TEXT, XMLReader::CDATA, XMLReader::WHITESPACE])) {
                $result .= $this->value;
            }
        }
        return $result;

    }

    /**
     * Parses the current XML element.
     *
     * This method returns arn array with 3 properties:
     *   * name - A clark-notation XML element name.
     *   * value - The parsed value.
     *   * attributes - A key-value list of attributes.
     *
     * @return array
     */
    function parseCurrentElement() {

        $name = $this->getClark();

        $attributes = [];

        if ($this->hasAttributes) {
            $attributes = $this->parseAttributes();
        }

        $value = call_user_func(
            $this->getDeserializerForElementName($name),
            $this
        );

        return [
            'name'       => $name,
            'value'      => $value,
            'attributes' => $attributes,
        ];
    }


    /**
     * Grabs all the attributes from the current element, and returns them as a
     * key-value array.
     *
     * If the attributes are part of the same namespace, they will simply be
     * short keys. If they are defined on a different namespace, the attribute
     * name will be retured in clark-notation.
     *
     * @return array
     */
    function parseAttributes() {

        $attributes = [];

        while ($this->moveToNextAttribute()) {
            if ($this->namespaceURI) {

                // Ignoring 'xmlns', it doesn't make any sense.
                if ($this->namespaceURI === 'http://www.w3.org/2000/xmlns/') {
                    continue;
                }

                $name = $this->getClark();
                $attributes[$name] = $this->value;

            } else {
                $attributes[$this->localName] = $this->value;
            }
        }
        $this->moveToElement();

        return $attributes;

    }

    /**
     * Returns the function that should be used to parse the element identified
     * by it's clark-notation name.
     *
     * @param string $name
     * @return callable
     */
    function getDeserializerForElementName($name) {

        if (!array_key_exists($name, $this->elementMap)) {
            return ['Sabre\\Xml\\Element\\Base', 'xmlDeserialize'];
        }

        $deserializer = $this->elementMap[$name];
        if (is_subclass_of($deserializer, 'Sabre\\Xml\\XmlDeserializable')) {
            return [ $deserializer, 'xmlDeserialize' ];
        }

        if (is_callable($deserializer)) {
            return $deserializer;
        }

        $type = gettype($deserializer);
        if ($type === 'string') {
            $type .= ' (' . $deserializer . ')';
        } elseif ($type === 'object') {
            $type .= ' (' . get_class($deserializer) . ')';
        }
        throw new \LogicException('Could not use this type as a deserializer: ' . $type . ' for element: ' . $name);

    }

}