Completed
Pull Request — master (#929)
by Asmir
02:40
created

DeserializationGraphNavigator   A

Complexity

Total Complexity 35

Size/Duplication

Total Lines 190
Duplicated Lines 0 %

Test Coverage

Coverage 81.93%

Importance

Changes 0
Metric Value
dl 0
loc 190
ccs 68
cts 83
cp 0.8193
rs 9
c 0
b 0
f 0
wmc 35

4 Methods

Rating   Name   Duplication   Size   Complexity  
D accept() 0 109 27
A __construct() 0 15 3
A resolveMetadata() 0 14 2
A afterVisitingObject() 0 11 3
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\GraphNavigator;
22
23
use JMS\Serializer\Accessor\AccessorStrategyInterface;
24
use JMS\Serializer\Construction\ObjectConstructorInterface;
25
use JMS\Serializer\DeserializationContext;
26
use JMS\Serializer\DeserializationVisitorInterface;
27
use JMS\Serializer\EventDispatcher\EventDispatcher;
28
use JMS\Serializer\EventDispatcher\EventDispatcherInterface;
29
use JMS\Serializer\EventDispatcher\ObjectEvent;
30
use JMS\Serializer\EventDispatcher\PreDeserializeEvent;
31
use JMS\Serializer\Exception\ExpressionLanguageRequiredException;
32
use JMS\Serializer\Exception\LogicException;
33
use JMS\Serializer\Exception\NotAcceptableException;
34
use JMS\Serializer\Exception\RuntimeException;
35
use JMS\Serializer\Exclusion\ExpressionLanguageExclusionStrategy;
36
use JMS\Serializer\Expression\ExpressionEvaluatorInterface;
37
use JMS\Serializer\GraphNavigator;
38
use JMS\Serializer\GraphNavigatorInterface;
39
use JMS\Serializer\Handler\HandlerRegistryInterface;
40
use JMS\Serializer\Metadata\ClassMetadata;
41
use JMS\Serializer\NullAwareVisitorInterface;
42
use Metadata\MetadataFactoryInterface;
43
44
/**
45
 * Handles traversal along the object graph.
46
 *
47
 * This class handles traversal along the graph, and calls different methods
48
 * on visitors, or custom handlers to process its nodes.
49
 *
50
 * @author Johannes M. Schmitt <[email protected]>
51
 */
52
final class DeserializationGraphNavigator extends GraphNavigator implements GraphNavigatorInterface
53
{
54
    /**
55
     * @var DeserializationVisitorInterface
56
     */
57
    protected $visitor;
58
59
    /**
60
     * @var DeserializationContext
61
     */
62
    protected $context;
63
64
    /**
65
     * @var ExpressionLanguageExclusionStrategy
66
     */
67
    private $expressionExclusionStrategy;
68
69
    private $dispatcher;
70
    private $metadataFactory;
71
    private $handlerRegistry;
72
    private $objectConstructor;
73
    /**
74
     * @var AccessorStrategyInterface
75
     */
76
    private $accessor;
77
78 136
    public function __construct(
79
        MetadataFactoryInterface $metadataFactory,
80
        HandlerRegistryInterface $handlerRegistry,
81
        ObjectConstructorInterface $objectConstructor,
82
        AccessorStrategyInterface $accessor,
83
        EventDispatcherInterface $dispatcher = null,
84
        ExpressionEvaluatorInterface $expressionEvaluator = null
85
    ) {
86 136
        $this->dispatcher = $dispatcher ?: new EventDispatcher();
87 136
        $this->metadataFactory = $metadataFactory;
88 136
        $this->handlerRegistry = $handlerRegistry;
89 136
        $this->objectConstructor = $objectConstructor;
90 136
        $this->accessor = $accessor;
91 136
        if ($expressionEvaluator) {
92 1
            $this->expressionExclusionStrategy = new ExpressionLanguageExclusionStrategy($expressionEvaluator);
93
        }
94 136
    }
95
96
    /**
97
     * Called for each node of the graph that is being traversed.
98
     *
99
     * @param mixed $data the data depends on the direction, and type of visitor
100
     * @param null|array $type array has the format ["name" => string, "params" => array]
101
     * @return mixed the return value depends on the direction, and type of visitor
102
     */
103 131
    public function accept($data, array $type = null)
104
    {
105
        // If the type was not given, we infer the most specific type from the
106
        // input data in serialization mode.
107 131
        if (null === $type) {
108
            throw new RuntimeException('The type must be given for all properties when deserializing.');
109
        }
110
        // Sometimes data can convey null but is not of a null type.
111
        // Visitors can have the power to add this custom null evaluation
112 131
        if ($this->visitor instanceof NullAwareVisitorInterface && $this->visitor->isNull($data) === true) {
113 13
            $type = ['name' => 'NULL', 'params' => []];
114
        }
115
116 131
        switch ($type['name']) {
117 131
            case 'NULL':
118 15
                return $this->visitor->visitNull($data, $type);
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->visitor->visitNull($data, $type) targeting JMS\Serializer\Deseriali...rInterface::visitNull() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
119
120 117
            case 'string':
121 46
                return $this->visitor->visitString($data, $type);
122
123 112
            case 'int':
124 112
            case 'integer':
125 17
                return $this->visitor->visitInteger($data, $type);
126
127 108
            case 'bool':
128 108
            case 'boolean':
129 13
                return $this->visitor->visitBoolean($data, $type);
130
131 100
            case 'double':
132 94
            case 'float':
133 25
                return $this->visitor->visitDouble($data, $type);
134
135 88
            case 'array':
136 36
                return $this->visitor->visitArray($data, $type);
137
138 76
            case 'resource':
139
                throw new RuntimeException('Resources are not supported in serialized data.');
140
141
            default:
142
143 76
                $this->context->increaseDepth();
144
145
                // Trigger pre-serialization callbacks, and listeners if they exist.
146
                // Dispatch pre-serialization event before handling data to have ability change type in listener
147 76
                if ($this->dispatcher->hasListeners('serializer.pre_deserialize', $type['name'], $this->format)) {
148
                    $this->dispatcher->dispatch('serializer.pre_deserialize', $type['name'], $this->format, $event = new PreDeserializeEvent($this->context, $data, $type));
149
                    $type = $event->getType();
150
                    $data = $event->getData();
151
                }
152
153
                // First, try whether a custom handler exists for the given type. This is done
154
                // before loading metadata because the type name might not be a class, but
155
                // could also simply be an artifical type.
156 76
                if (null !== $handler = $this->handlerRegistry->getHandler(GraphNavigatorInterface::DIRECTION_DESERIALIZATION, $type['name'], $this->format)) {
157 26
                    $rs = \call_user_func($handler, $this->visitor, $data, $type, $this->context);
158 26
                    $this->context->decreaseDepth();
159
160 26
                    return $rs;
161
                }
162
163
                /** @var $metadata ClassMetadata */
164 65
                $metadata = $this->metadataFactory->getMetadataForClass($type['name']);
165
166 65
                if ($metadata->usingExpression && !$this->expressionExclusionStrategy) {
167
                    throw new ExpressionLanguageRequiredException("To use conditional exclude/expose in {$metadata->name} you must configure the expression language.");
168
                }
169
170 65
                if (!empty($metadata->discriminatorMap) && $type['name'] === $metadata->discriminatorBaseClass) {
171 14
                    $metadata = $this->resolveMetadata($data, $metadata);
172
                }
173
174 63
                if ($this->exclusionStrategy->shouldSkipClass($metadata, $this->context)) {
175
                    $this->context->decreaseDepth();
176
177
                    return null;
178
                }
179
180 63
                $this->context->pushClassMetadata($metadata);
181
182 63
                $object = $this->objectConstructor->construct($this->visitor, $metadata, $data, $type, $this->context);
183
184 63
                $this->visitor->startVisitingObject($metadata, $object, $type);
185 63
                foreach ($metadata->propertyMetadata as $propertyMetadata) {
0 ignored issues
show
Bug introduced by
The property propertyMetadata does not seem to exist on Metadata\ClassHierarchyMetadata.
Loading history...
186 63
                    if ($this->exclusionStrategy->shouldSkipProperty($propertyMetadata, $this->context)) {
187
                        continue;
188
                    }
189
190 63
                    if (null !== $this->expressionExclusionStrategy && $this->expressionExclusionStrategy->shouldSkipProperty($propertyMetadata, $this->context)) {
191
                        continue;
192
                    }
193
194 63
                    if ($propertyMetadata->readOnly) {
195 18
                        continue;
196
                    }
197
198 59
                    $this->context->pushPropertyMetadata($propertyMetadata);
199
                    try {
200 59
                        $v = $this->visitor->visitProperty($propertyMetadata, $data);
201 59
                        $this->accessor->setValue($object, $v, $propertyMetadata);
202 4
                    }catch (NotAcceptableException $e){
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
203
204
                    }
205 59
                    $this->context->popPropertyMetadata();
206
                }
207
208 62
                $rs = $this->visitor->endVisitingObject($metadata, $data, $type);
209 62
                $this->afterVisitingObject($metadata, $rs, $type);
210
211 62
                return $rs;
212
        }
213
    }
214
215 14
    private function resolveMetadata($data, ClassMetadata $metadata)
216
    {
217 14
        $typeValue = $this->visitor->visitDiscriminatorMapProperty($data, $metadata);
218
219 12
        if (!isset($metadata->discriminatorMap[$typeValue])) {
220
            throw new LogicException(sprintf(
221
                'The type value "%s" does not exist in the discriminator map of class "%s". Available types: %s',
222
                $typeValue,
223
                $metadata->name,
224
                implode(', ', array_keys($metadata->discriminatorMap))
225
            ));
226
        }
227
228 12
        return $this->metadataFactory->getMetadataForClass($metadata->discriminatorMap[$typeValue]);
229
    }
230
231 62
    private function afterVisitingObject(ClassMetadata $metadata, $object, array $type): void
232
    {
233 62
        $this->context->decreaseDepth();
234 62
        $this->context->popClassMetadata();
235
236 62
        foreach ($metadata->postDeserializeMethods as $method) {
237 4
            $method->invoke($object);
238
        }
239
240 62
        if ($this->dispatcher->hasListeners('serializer.post_deserialize', $metadata->name, $this->format)) {
241 1
            $this->dispatcher->dispatch('serializer.post_deserialize', $metadata->name, $this->format, new ObjectEvent($this->context, $object, $type));
242
        }
243 62
    }
244
}
245