Passed
Pull Request — master (#925)
by Asmir
02:44
created

XmlDeserializationVisitor::getResult()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * Copyright 2016 Johannes M. Schmitt <[email protected]>
7
 *
8
 * Licensed under the Apache License, Version 2.0 (the "License");
9
 * you may not use this file except in compliance with the License.
10
 * You may obtain a copy of the License at
11
 *
12
 *     http://www.apache.org/licenses/LICENSE-2.0
13
 *
14
 * Unless required by applicable law or agreed to in writing, software
15
 * distributed under the License is distributed on an "AS IS" BASIS,
16
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
 * See the License for the specific language governing permissions and
18
 * limitations under the License.
19
 */
20
21
namespace JMS\Serializer;
22
23
use JMS\Serializer\Accessor\AccessorStrategyInterface;
24
use JMS\Serializer\Exception\InvalidArgumentException;
25
use JMS\Serializer\Exception\LogicException;
26
use JMS\Serializer\Exception\NotAcceptableException;
27
use JMS\Serializer\Exception\RuntimeException;
28
use JMS\Serializer\Exception\XmlErrorException;
29
use JMS\Serializer\Metadata\ClassMetadata;
30
use JMS\Serializer\Metadata\PropertyMetadata;
31
32
class XmlDeserializationVisitor extends AbstractVisitor implements NullAwareVisitorInterface, DeserializationVisitorInterface
33
{
34
    private $objectStack;
35
    private $metadataStack;
36
    private $objectMetadataStack;
37
    private $currentObject;
38
    private $currentMetadata;
39
    private $disableExternalEntities = true;
40
    private $doctypeWhitelist = array();
41
42 69
    public function __construct(
43
        bool $disableExternalEntities = true, array $doctypeWhitelist = array())
44
    {
45 69
        $this->objectStack = new \SplStack;
46 69
        $this->metadataStack = new \SplStack;
47 69
        $this->objectMetadataStack = new \SplStack;
48 69
        $this->disableExternalEntities = $disableExternalEntities;
49 69
        $this->doctypeWhitelist = $doctypeWhitelist;
50 69
    }
51
52 68
    public function prepare($data)
53
    {
54 68
        $data = $this->emptyStringToSpaceCharacter($data);
55
56 68
        $previous = libxml_use_internal_errors(true);
57 68
        libxml_clear_errors();
58
59 68
        $previousEntityLoaderState = libxml_disable_entity_loader($this->disableExternalEntities);
60
61 68
        if (false !== stripos($data, '<!doctype')) {
62 2
            $internalSubset = $this->getDomDocumentTypeEntitySubset($data);
63 2
            if (!in_array($internalSubset, $this->doctypeWhitelist, true)) {
64 2
                throw new InvalidArgumentException(sprintf(
65 2
                    'The document type "%s" is not allowed. If it is safe, you may add it to the whitelist configuration.',
66 2
                    $internalSubset
67
                ));
68
            }
69
        }
70
71 66
        $doc = simplexml_load_string($data);
72
73 66
        libxml_use_internal_errors($previous);
74 66
        libxml_disable_entity_loader($previousEntityLoaderState);
75
76 66
        if (false === $doc) {
77 1
            throw new XmlErrorException(libxml_get_last_error());
78
        }
79
80 65
        return $doc;
81
    }
82
83 68
    private function emptyStringToSpaceCharacter($data)
84
    {
85 68
        return $data === '' ? ' ' : (string)$data;
86
    }
87
88 13
    public function visitNull($data, array $type): void
89
    {
90
91 13
    }
92
93 23
    public function visitString($data, array $type): string
94
    {
95 23
        return (string)$data;
96
    }
97
98 8
    public function visitBoolean($data, array $type): bool
99
    {
100 8
        $data = (string)$data;
101
102 8
        if ('true' === $data || '1' === $data) {
103 4
            return true;
104 5
        } elseif ('false' === $data || '0' === $data) {
105 5
            return false;
106
        } else {
107
            throw new RuntimeException(sprintf('Could not convert data to boolean. Expected "true", "false", "1" or "0", but got %s.', json_encode($data)));
108
        }
109
    }
110
111 8
    public function visitInteger($data, array $type): int
112
    {
113 8
        return (integer)$data;
114
    }
115
116 10
    public function visitDouble($data, array $type): float
117
    {
118 10
        return (double)$data;
119
    }
120
121 18
    public function visitArray($data, array $type): array
122
    {
123
        // handle key-value-pairs
124 18
        if (null !== $this->currentMetadata && $this->currentMetadata->xmlKeyValuePairs) {
125 2
            if (2 !== count($type['params'])) {
126
                throw new RuntimeException('The array type must be specified as "array<K,V>" for Key-Value-Pairs.');
127
            }
128 2
            $this->revertCurrentMetadata();
129
130 2
            list($keyType, $entryType) = $type['params'];
131
132 2
            $result = [];
133 2
            foreach ($data as $key => $v) {
134 2
                $k = $this->navigator->accept($key, $keyType);
135 2
                $result[$k] = $this->navigator->accept($v, $entryType);
136
            }
137
138 2
            return $result;
139
        }
140
141 18
        $entryName = null !== $this->currentMetadata && $this->currentMetadata->xmlEntryName ? $this->currentMetadata->xmlEntryName : 'entry';
142 18
        $namespace = null !== $this->currentMetadata && $this->currentMetadata->xmlEntryNamespace ? $this->currentMetadata->xmlEntryNamespace : null;
143
144 18
        if ($namespace === null && $this->objectMetadataStack->count()) {
145 13
            $classMetadata = $this->objectMetadataStack->top();
146 13
            $namespace = isset($classMetadata->xmlNamespaces['']) ? $classMetadata->xmlNamespaces[''] : $namespace;
147 13
            if ($namespace === null) {
148 10
                $namespaces = $data->getDocNamespaces();
149 10
                if (isset($namespaces[''])) {
150 1
                    $namespace = $namespaces[''];
151
                }
152
            }
153
        }
154
155 18
        if (null !== $namespace) {
156 5
            $prefix = uniqid('ns-');
157 5
            $data->registerXPathNamespace($prefix, $namespace);
158 5
            $nodes = $data->xpath("$prefix:$entryName");
159
        } else {
160 14
            $nodes = $data->xpath($entryName);
161
        }
162
163 18
        if (!\count($nodes)) {
164 4
            return array();
165
        }
166
167 18
        switch (\count($type['params'])) {
168 18
            case 0:
169
                throw new RuntimeException(sprintf('The array type must be specified either as "array<T>", or "array<K,V>".'));
170
171 18
            case 1:
172 18
                $result = array();
173
174 18
                foreach ($nodes as $v) {
175 18
                    $result[] = $this->navigator->accept($v, $type['params'][0]);
176
                }
177
178 18
                return $result;
179
180 4
            case 2:
181 4
                if (null === $this->currentMetadata) {
182
                    throw new RuntimeException('Maps are not supported on top-level without metadata.');
183
                }
184
185 4
                list($keyType, $entryType) = $type['params'];
186 4
                $result = array();
187
188 4
                $nodes = $data->children($namespace)->$entryName;
189 4
                foreach ($nodes as $v) {
190 4
                    $attrs = $v->attributes();
191 4
                    if (!isset($attrs[$this->currentMetadata->xmlKeyAttribute])) {
192
                        throw new RuntimeException(sprintf('The key attribute "%s" must be set for each entry of the map.', $this->currentMetadata->xmlKeyAttribute));
193
                    }
194
195 4
                    $k = $this->navigator->accept($attrs[$this->currentMetadata->xmlKeyAttribute], $keyType);
196 4
                    $result[$k] = $this->navigator->accept($v, $entryType);
197
                }
198
199 4
                return $result;
200
201
            default:
202
                throw new LogicException(sprintf('The array type does not support more than 2 parameters, but got %s.', json_encode($type['params'])));
203
        }
204
    }
205
206 7
    public function visitDiscriminatorMapProperty($data, ClassMetadata $metadata): string
207
    {
208
        switch (true) {
209
            // Check XML attribute for discriminatorFieldName
210 7
            case $metadata->xmlDiscriminatorAttribute && isset($data[$metadata->discriminatorFieldName]):
211 1
                return (string)$data[$metadata->discriminatorFieldName];
212
213
            // Check XML element with namespace for discriminatorFieldName
214 6
            case !$metadata->xmlDiscriminatorAttribute && null !== $metadata->xmlDiscriminatorNamespace && isset($data->children($metadata->xmlDiscriminatorNamespace)->{$metadata->discriminatorFieldName}):
215 1
                return (string)$data->children($metadata->xmlDiscriminatorNamespace)->{$metadata->discriminatorFieldName};
216
217
            // Check XML element for discriminatorFieldName
218 5
            case isset($data->{$metadata->discriminatorFieldName}):
219 4
                return (string)$data->{$metadata->discriminatorFieldName};
220
221
            default:
222 1
                throw new LogicException(sprintf(
223 1
                    'The discriminator field name "%s" for base-class "%s" was not found in input data.',
224 1
                    $metadata->discriminatorFieldName,
225 1
                    $metadata->name
226
                ));
227
        }
228
    }
229
230 31
    public function startVisitingObject(ClassMetadata $metadata, object $object, array $type): void
231
    {
232 31
        $this->setCurrentObject($object);
233 31
        $this->objectMetadataStack->push($metadata);
234 31
    }
235
236 28
    public function visitProperty(PropertyMetadata $metadata, $data)
237
    {
238 28
        $name = $metadata->serializedName;
239
240 28
        if (!$metadata->type) {
241
            throw new RuntimeException(sprintf('You must define a type for %s::$%s.', $metadata->reflection->class, $metadata->name));
242
        }
243
244 28
        if ($metadata->xmlAttribute) {
245
246 6
            $attributes = $data->attributes($metadata->xmlNamespace);
247 6
            if (isset($attributes[$name])) {
248 6
                return $this->navigator->accept($attributes[$name], $metadata->type);
249
            }
250
251
            throw new NotAcceptableException();
252
        }
253
254 28
        if ($metadata->xmlValue) {
255 7
            return $this->navigator->accept($data, $metadata->type);
256
        }
257
258 26
        if ($metadata->xmlCollection) {
259 7
            $enclosingElem = $data;
260 7
            if (!$metadata->xmlCollectionInline) {
261 6
                $enclosingElem = $data->children($metadata->xmlNamespace)->$name;
262
            }
263
264 7
            $this->setCurrentMetadata($metadata);
265 7
            $v = $this->navigator->accept($enclosingElem, $metadata->type);
266 7
            $this->revertCurrentMetadata();
267 7
            return $v;
268
        }
269
270 25
        if ($metadata->xmlNamespace) {
271 4
            $node = $data->children($metadata->xmlNamespace)->$name;
272 4
            if (!$node->count()) {
273 4
                throw new NotAcceptableException();
274
            }
275
        } else {
276
277 22
            $namespaces = $data->getDocNamespaces();
278
279 22
            if (isset($namespaces[''])) {
280 2
                $prefix = uniqid('ns-');
281 2
                $data->registerXPathNamespace($prefix, $namespaces['']);
282 2
                $nodes = $data->xpath('./' . $prefix . ':' . $name);
283
            } else {
284 20
                $nodes = $data->xpath('./' . $name);
285
            }
286 22
            if (empty($nodes)) {
287 2
                throw new NotAcceptableException();
288
            }
289 22
            $node = reset($nodes);
290
        }
291
292 24
        if ($metadata->xmlKeyValuePairs) {
293 2
            $this->setCurrentMetadata($metadata);
294
        }
295
296 24
        return $this->navigator->accept($node, $metadata->type);
297
    }
298
299
    /**
300
     * @param ClassMetadata $metadata
301
     * @param mixed $data
302
     * @param array $type
303
     * @return mixed
304
     */
305 31
    public function endVisitingObject(ClassMetadata $metadata, $data, array $type) : object
306
    {
307 31
        $rs = $this->currentObject;
308 31
        $this->objectMetadataStack->pop();
309 31
        $this->revertCurrentObject();
310
311 31
        return $rs;
312
    }
313
314 31
    public function setCurrentObject($object)
315
    {
316 31
        $this->objectStack->push($this->currentObject);
317 31
        $this->currentObject = $object;
318 31
    }
319
320
    public function getCurrentObject()
321
    {
322
        return $this->currentObject;
323
    }
324
325 31
    public function revertCurrentObject()
326
    {
327 31
        return $this->currentObject = $this->objectStack->pop();
328
    }
329
330 9
    public function setCurrentMetadata(PropertyMetadata $metadata)
331
    {
332 9
        $this->metadataStack->push($this->currentMetadata);
333 9
        $this->currentMetadata = $metadata;
334 9
    }
335
336
    public function getCurrentMetadata()
337
    {
338
        return $this->currentMetadata;
339
    }
340
341 9
    public function revertCurrentMetadata()
342
    {
343 9
        return $this->currentMetadata = $this->metadataStack->pop();
344
    }
345
346 64
    public function getResult($data)
347
    {
348 64
        return $data;
349
    }
350
351
    /**
352
     * Retrieves internalSubset even in bugfixed php versions
353
     *
354
     * @param string $data
355
     * @return string
356
     */
357 2
    private function getDomDocumentTypeEntitySubset($data)
358
    {
359 2
        $startPos = $endPos = stripos($data, '<!doctype');
360 2
        $braces = 0;
361
        do {
362 2
            $char = $data[$endPos++];
363 2
            if ($char === '<') {
364 2
                ++$braces;
365
            }
366 2
            if ($char === '>') {
367 2
                --$braces;
368
            }
369 2
        } while ($braces > 0);
370
371 2
        $internalSubset = substr($data, $startPos, $endPos - $startPos);
372 2
        $internalSubset = str_replace(array("\n", "\r"), '', $internalSubset);
373 2
        $internalSubset = preg_replace('/\s{2,}/', ' ', $internalSubset);
374 2
        $internalSubset = str_replace(array("[ <!", "> ]>"), array('[<!', '>]>'), $internalSubset);
375
376 2
        return $internalSubset;
377
    }
378
379
    /**
380
     * @param mixed $value
381
     *
382
     * @return bool
383
     */
384 66
    public function isNull($value): bool
385
    {
386 66
        if ($value instanceof \SimpleXMLElement) {
387
            // Workaround for https://bugs.php.net/bug.php?id=75168 and https://github.com/schmittjoh/serializer/issues/817
388
            // If the "name" is empty means that we are on an not-existent node and subsequent operations on the object will trigger the warning:
389
            // "Node no longer exists"
390 66
            if ($value->getName() === "") {
391
                // @todo should be "true", but for collections needs a default collection value. maybe something for the 2.0
392 2
                return false;
393
            }
394
395 66
            $xsiAttributes = $value->attributes('http://www.w3.org/2001/XMLSchema-instance');
396 66
            if (isset($xsiAttributes['nil'])
397 66
                && ((string)$xsiAttributes['nil'] === 'true' || (string)$xsiAttributes['nil'] === '1')
398
            ) {
399 14
                return true;
400
            }
401
        }
402
403 54
        return $value === null;
404
    }
405
}
406