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

SerializationGraphNavigator::__construct()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 15
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 6
nc 2
nop 5
dl 0
loc 15
ccs 7
cts 7
cp 1
crap 3
rs 9.4285
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\GraphNavigator;
22
23
use JMS\Serializer\Accessor\AccessorStrategyInterface;
24
use JMS\Serializer\Construction\ObjectConstructorInterface;
25
use JMS\Serializer\Context;
26
use JMS\Serializer\EventDispatcher\EventDispatcher;
27
use JMS\Serializer\EventDispatcher\EventDispatcherInterface;
28
use JMS\Serializer\EventDispatcher\ObjectEvent;
29
use JMS\Serializer\EventDispatcher\PreDeserializeEvent;
30
use JMS\Serializer\EventDispatcher\PreSerializeEvent;
31
use JMS\Serializer\Exception\CircularReferenceDetectedException;
32
use JMS\Serializer\Exception\ExcludedClassException;
33
use JMS\Serializer\Exception\ExpressionLanguageRequiredException;
34
use JMS\Serializer\Exception\InvalidArgumentException;
35
use JMS\Serializer\Exception\NotAcceptableException;
36
use JMS\Serializer\Exception\RuntimeException;
37
use JMS\Serializer\Exclusion\ExclusionStrategyInterface;
38
use JMS\Serializer\Exclusion\ExpressionLanguageExclusionStrategy;
39
use JMS\Serializer\Expression\ExpressionEvaluatorInterface;
40
use JMS\Serializer\GraphNavigator;
41
use JMS\Serializer\GraphNavigatorInterface;
42
use JMS\Serializer\Handler\HandlerRegistryInterface;
43
use JMS\Serializer\Metadata\ClassMetadata;
44
use JMS\Serializer\NullAwareVisitorInterface;
45
use JMS\Serializer\SerializationContext;
46
use JMS\Serializer\SerializationVisitorInterface;
47
use JMS\Serializer\VisitorInterface;
48
use Metadata\MetadataFactoryInterface;
49
50
/**
51
 * Handles traversal along the object graph.
52
 *
53
 * This class handles traversal along the graph, and calls different methods
54
 * on visitors, or custom handlers to process its nodes.
55
 *
56
 * @author Johannes M. Schmitt <[email protected]>
57
 */
58
final class SerializationGraphNavigator extends GraphNavigator implements GraphNavigatorInterface
59
{
60
    /**
61
     * @var SerializationVisitorInterface
62
     */
63
    protected $visitor;
64
65
    /**
66
     * @var SerializationContext
67
     */
68
    protected $context;
69
70
    /**
71
     * @var ExpressionLanguageExclusionStrategy
72
     */
73
    private $expressionExclusionStrategy;
74
75
    private $dispatcher;
76
    private $metadataFactory;
77
    private $handlerRegistry;
78
    /**
79
     * @var AccessorStrategyInterface
80
     */
81
    private $accessor;
82
83
    /**
84
     * @var bool
85
     */
86
    private $shouldSerializeNull;
87
88 276
    public function __construct(
89
        MetadataFactoryInterface $metadataFactory,
90
        HandlerRegistryInterface $handlerRegistry,
91
        AccessorStrategyInterface $accessor,
92
        EventDispatcherInterface $dispatcher = null,
93
        ExpressionEvaluatorInterface $expressionEvaluator = null
94
    )
95
    {
96 276
        $this->dispatcher = $dispatcher ?: new EventDispatcher();
97 276
        $this->metadataFactory = $metadataFactory;
98 276
        $this->handlerRegistry = $handlerRegistry;
99 276
        $this->accessor = $accessor;
100
101 276
        if ($expressionEvaluator) {
102 23
            $this->expressionExclusionStrategy = new ExpressionLanguageExclusionStrategy($expressionEvaluator);
103
        }
104 276
    }
105
106 276
    public function initialize(VisitorInterface $visitor, Context $context):void
107
    {
108 276
        parent::initialize($visitor, $context);
109 276
        $this->shouldSerializeNull = $context->shouldSerializeNull();
110 276
    }
111
112
    /**
113
     * Called for each node of the graph that is being traversed.
114
     *
115
     * @param mixed $data the data depends on the direction, and type of visitor
116
     * @param null|array $type array has the format ["name" => string, "params" => array]
117
     * @return mixed the return value depends on the direction, and type of visitor
118
     */
119 275
    public function accept($data, array $type = null)
120
    {
121
        // If the type was not given, we infer the most specific type from the
122
        // input data in serialization mode.
123 275
        if (null === $type) {
124
125 255
            $typeName = \gettype($data);
126 255
            if ('object' === $typeName) {
127 181
                $typeName = \get_class($data);
128
            }
129
130 255
            $type = ['name' => $typeName, 'params' => []];
131
        }
132
        // If the data is null, we have to force the type to null regardless of the input in order to
133
        // guarantee correct handling of null values, and not have any internal auto-casting behavior.
134 142
        else if (null === $data) {
135 5
            $type = ['name' => 'NULL', 'params' => []];
136
        }
137
        // Sometimes data can convey null but is not of a null type.
138
        // Visitors can have the power to add this custom null evaluation
139 275
        if ($this->visitor instanceof NullAwareVisitorInterface && $this->visitor->isNull($data) === true) {
140
            $type = ['name' => 'NULL', 'params' => []];
141
        }
142
143 275
        switch ($type['name']) {
144 275
            case 'NULL':
145 38
                if (!$this->shouldSerializeNull) {
146 15
                    throw new NotAcceptableException();
147
                }
148 23
                return $this->visitor->visitNull($data, $type);
149
150 251
            case 'string':
151 157
                return $this->visitor->visitString((string)$data, $type);
152
153 247
            case 'int':
154 247
            case 'integer':
155 42
                return $this->visitor->visitInteger((int)$data, $type);
156
157 244
            case 'bool':
158 244
            case 'boolean':
159 13
                return $this->visitor->visitBoolean((bool)$data, $type);
160
161 239
            case 'double':
162 230
            case 'float':
163 20
                return $this->visitor->visitDouble((float)$data, $type);
164
165 230
            case 'array':
166 100
                return $this->visitor->visitArray((array)$data, $type);
167
168 192
            case 'resource':
169 1
                $msg = 'Resources are not supported in serialized data.';
170 1
                if (null !== $path = $this->context->getPath()) {
0 ignored issues
show
introduced by
The condition null !== $path = $this->context->getPath() is always true.
Loading history...
171 1
                    $msg .= ' Path: ' . $path;
172
                }
173
174 1
                throw new RuntimeException($msg);
175
176
            default:
177
178 191
                if (null !== $data) {
179 191
                    if ($this->context->isVisiting($data)) {
180 4
                        throw new CircularReferenceDetectedException();
181
                    }
182 191
                    $this->context->startVisiting($data);
183
                }
184
185
                // If we're serializing a polymorphic type, then we'll be interested in the
186
                // metadata for the actual type of the object, not the base class.
187 191
                if (class_exists($type['name'], false) || interface_exists($type['name'], false)) {
188 191
                    if (is_subclass_of($data, $type['name'], false)) {
189 4
                        $type = ['name' => \get_class($data), 'params' => []];
190
                    }
191
                }
192
193
                // Trigger pre-serialization callbacks, and listeners if they exist.
194
                // Dispatch pre-serialization event before handling data to have ability change type in listener
195 191
                if ($this->dispatcher->hasListeners('serializer.pre_serialize', $type['name'], $this->format)) {
196 190
                    $this->dispatcher->dispatch('serializer.pre_serialize', $type['name'], $this->format, $event = new PreSerializeEvent($this->context, $data, $type));
197 190
                    $type = $event->getType();
198
                }
199
200
                // First, try whether a custom handler exists for the given type. This is done
201
                // before loading metadata because the type name might not be a class, but
202
                // could also simply be an artifical type.
203 191
                if (null !== $handler = $this->handlerRegistry->getHandler(GraphNavigatorInterface::DIRECTION_SERIALIZATION, $type['name'], $this->format)) {
204 47
                    $rs = \call_user_func($handler, $this->visitor, $data, $type, $this->context);
205 47
                    $this->context->stopVisiting($data);
206
207 47
                    return $rs;
208
                }
209
210
211
                /** @var $metadata ClassMetadata */
212 169
                $metadata = $this->metadataFactory->getMetadataForClass($type['name']);
213
214 167
                if ($metadata->usingExpression && $this->expressionExclusionStrategy === null) {
215 2
                    throw new ExpressionLanguageRequiredException("To use conditional exclude/expose in {$metadata->name} you must configure the expression language.");
216
                }
217
218 165
                if ($this->exclusionStrategy->shouldSkipClass($metadata, $this->context)) {
219 10
                    $this->context->stopVisiting($data);
220
221 10
                    throw new ExcludedClassException();
222
                }
223
224 161
                $this->context->pushClassMetadata($metadata);
225
226 161
                foreach ($metadata->preSerializeMethods as $method) {
227 2
                    $method->invoke($data);
228
                }
229
230 161
                $this->visitor->startVisitingObject($metadata, $data, $type);
231 161
                foreach ($metadata->propertyMetadata as $propertyMetadata) {
232 160
                    if ($this->exclusionStrategy->shouldSkipProperty($propertyMetadata, $this->context)) {
233 16
                        continue;
234
                    }
235
236 160
                    if (null !== $this->expressionExclusionStrategy && $this->expressionExclusionStrategy->shouldSkipProperty($propertyMetadata, $this->context)) {
237 16
                        continue;
238
                    }
239
240 160
                    $v = $this->accessor->getValue($data, $propertyMetadata);
241
242 158
                    if (null === $v && $this->shouldSerializeNull !== true) {
243 22
                        continue;
244
                    }
245
246 156
                    $this->context->pushPropertyMetadata($propertyMetadata);
247 156
                    $this->visitor->visitProperty($propertyMetadata, $v);
248 155
                    $this->context->popPropertyMetadata();
249
                }
250
251 157
                $this->afterVisitingObject($metadata, $data, $type);
252
253 157
                return $this->visitor->endVisitingObject($metadata, $data, $type);
254
        }
255
    }
256
257 157
    private function afterVisitingObject(ClassMetadata $metadata, $object, array $type)
258
    {
259 157
        $this->context->stopVisiting($object);
260 157
        $this->context->popClassMetadata();
261
262 157
        foreach ($metadata->postSerializeMethods as $method) {
263 2
            $method->invoke($object);
264
        }
265
266 157
        if ($this->dispatcher->hasListeners('serializer.post_serialize', $metadata->name, $this->format)) {
267 2
            $this->dispatcher->dispatch('serializer.post_serialize', $metadata->name, $this->format, new ObjectEvent($this->context, $object, $type));
268
        }
269 157
    }
270
}
271