Debian Codegraph @

lib/3rdParty/composer/symfony/serializer/Serializer.php

raw symbols SCIP
1 <?php
2
3 /*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <[email protected]>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Symfony\Component\Serializer;
13
14 use Symfony\Component\Serializer\Encoder\ChainDecoder;
15 use Symfony\Component\Serializer\Encoder\ChainEncoder;
16 use Symfony\Component\Serializer\Encoder\ContextAwareDecoderInterface;
17 use Symfony\Component\Serializer\Encoder\ContextAwareEncoderInterface;
18 use Symfony\Component\Serializer\Encoder\DecoderInterface;
19 use Symfony\Component\Serializer\Encoder\EncoderInterface;
20 use Symfony\Component\Serializer\Exception\InvalidArgumentException;
21 use Symfony\Component\Serializer\Exception\LogicException;
22 use Symfony\Component\Serializer\Exception\NotNormalizableValueException;
23 use Symfony\Component\Serializer\Exception\PartialDenormalizationException;
24 use Symfony\Component\Serializer\Exception\UnsupportedFormatException;
25 use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer;
26 use Symfony\Component\Serializer\Normalizer\DenormalizerAwareInterface;
27 use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
28 use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
29 use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
30
31 /**
32 * Serializer serializes and deserializes data.
33 *
34 * objects are turned into arrays by normalizers.
35 * arrays are turned into various output formats by encoders.
36 *
37 * $serializer->serialize($obj, 'xml')
38 * $serializer->decode($data, 'xml')
39 * $serializer->denormalize($data, 'Class', 'xml')
40 *
41 * @author Jordi Boggiano <[email protected]>
42 * @author Johannes M. Schmitt <[email protected]>
43 * @author Lukas Kahwe Smith <[email protected]>
44 * @author Kévin Dunglas <[email protected]>
45 */
46 class Serializer implements SerializerInterface, NormalizerInterface, DenormalizerInterface, ContextAwareEncoderInterface, ContextAwareDecoderInterface
47 {
48 /**
49 * Flag to control whether an empty array should be transformed to an
50 * object (in JSON: {}) or to a list (in JSON: []).
51 */
52 public const EMPTY_ARRAY_AS_OBJECT = 'empty_array_as_object';
53
54 private const SCALAR_TYPES = [
55 'int' => true,
56 'bool' => true,
57 'float' => true,
58 'string' => true,
59 ];
60
61 protected ChainEncoder $encoder;
62
63 protected ChainDecoder $decoder;
64
65 /**
66 * @var array<string, array<string, array<bool>>>
67 */
68 private array $denormalizerCache = [];
69
70 /**
71 * @var array<string, array<string, array<bool>>>
72 */
73 private array $normalizerCache = [];
74
75 /**
76 * @param array<NormalizerInterface|DenormalizerInterface> $normalizers
77 * @param array<EncoderInterface|DecoderInterface> $encoders
78 * @param array<string, mixed> $defaultContext
79 */
80 public function __construct(
81 private array $normalizers = [],
82 array $encoders = [],
83 private array $defaultContext = [],
84 ) {
85 foreach ($normalizers as $normalizer) {
86 if ($normalizer instanceof SerializerAwareInterface) {
87 $normalizer->setSerializer($this);
88 }
89
90 if ($normalizer instanceof DenormalizerAwareInterface) {
91 $normalizer->setDenormalizer($this);
92 }
93
94 if ($normalizer instanceof NormalizerAwareInterface) {
95 $normalizer->setNormalizer($this);
96 }
97
98 if (!($normalizer instanceof NormalizerInterface || $normalizer instanceof DenormalizerInterface)) {
99 throw new InvalidArgumentException(\sprintf('The class "%s" neither implements "%s" nor "%s".', get_debug_type($normalizer), NormalizerInterface::class, DenormalizerInterface::class));
100 }
101 }
102
103 $decoders = [];
104 $realEncoders = [];
105 foreach ($encoders as $encoder) {
106 if ($encoder instanceof SerializerAwareInterface) {
107 $encoder->setSerializer($this);
108 }
109 if ($encoder instanceof DecoderInterface) {
110 $decoders[] = $encoder;
111 }
112 if ($encoder instanceof EncoderInterface) {
113 $realEncoders[] = $encoder;
114 }
115
116 if (!($encoder instanceof EncoderInterface || $encoder instanceof DecoderInterface)) {
117 throw new InvalidArgumentException(\sprintf('The class "%s" neither implements "%s" nor "%s".', get_debug_type($encoder), EncoderInterface::class, DecoderInterface::class));
118 }
119 }
120 $this->encoder = new ChainEncoder($realEncoders);
121 $this->decoder = new ChainDecoder($decoders);
122 }
123
124 final public function serialize(mixed $data, string $format, array $context = []): string
125 {
126 if (!$this->supportsEncoding($format, $context)) {
127 throw new UnsupportedFormatException(\sprintf('Serialization for the format "%s" is not supported.', $format));
128 }
129
130 if ($this->encoder->needsNormalization($format, $context)) {
131 $data = $this->normalize($data, $format, $context);
132 }
133
134 return $this->encode($data, $format, $context);
135 }
136
137 final public function deserialize(mixed $data, string $type, string $format, array $context = []): mixed
138 {
139 if (!$this->supportsDecoding($format, $context)) {
140 throw new UnsupportedFormatException(\sprintf('Deserialization for the format "%s" is not supported.', $format));
141 }
142
143 $data = $this->decode($data, $format, $context);
144
145 return $this->denormalize($data, $type, $format, $context);
146 }
147
148 public function normalize(mixed $data, ?string $format = null, array $context = []): array|string|int|float|bool|\ArrayObject|null
149 {
150 // If a normalizer supports the given data, use it
151 if ($normalizer = $this->getNormalizer($data, $format, $context)) {
152 return $normalizer->normalize($data, $format, $context);
153 }
154
155 if (null === $data || \is_scalar($data)) {
156 return $data;
157 }
158
159 if (\is_array($data) && !$data && ($context[self::EMPTY_ARRAY_AS_OBJECT] ?? $this->defaultContext[self::EMPTY_ARRAY_AS_OBJECT] ?? false)) {
160 return new \ArrayObject();
161 }
162
163 if (is_iterable($data)) {
164 if ($data instanceof \Countable && ($context[AbstractObjectNormalizer::PRESERVE_EMPTY_OBJECTS] ?? $this->defaultContext[AbstractObjectNormalizer::PRESERVE_EMPTY_OBJECTS] ?? false) && !\count($data)) {
165 return new \ArrayObject();
166 }
167
168 $normalized = [];
169 foreach ($data as $key => $val) {
170 $normalized[$key] = $this->normalize($val, $format, $context);
171 }
172
173 return $normalized;
174 }
175
176 if (\is_object($data)) {
177 if (!$this->normalizers) {
178 throw new LogicException('You must register at least one normalizer to be able to normalize objects.');
179 }
180
181 throw new NotNormalizableValueException(\sprintf('Could not normalize object of type "%s", no supporting normalizer found.', get_debug_type($data)));
182 }
183
184 throw new NotNormalizableValueException('An unexpected value could not be normalized: '.(!\is_resource($data) ? var_export($data, true) : \sprintf('"%s" resource', get_resource_type($data))));
185 }
186
187 /**
188 * @throws NotNormalizableValueException
189 * @throws PartialDenormalizationException Occurs when one or more properties of $type fails to denormalize
190 */
191 public function denormalize(mixed $data, string $type, ?string $format = null, array $context = []): mixed
192 {
193 if (isset($context[DenormalizerInterface::COLLECT_DENORMALIZATION_ERRORS], $context['not_normalizable_value_exceptions'])) {
194 throw new LogicException('Passing a value for "not_normalizable_value_exceptions" context key is not allowed.');
195 }
196
197 $normalizer = $this->getDenormalizer($data, $type, $format, $context);
198
199 // Check for a denormalizer first, e.g. the data is wrapped
200 if (!$normalizer && isset(self::SCALAR_TYPES[$type])) {
201 if (!('is_'.$type)($data)) {
202 throw NotNormalizableValueException::createForUnexpectedDataType(\sprintf('Data expected to be of type "%s" ("%s" given).', $type, get_debug_type($data)), $data, [$type], $context['deserialization_path'] ?? null, true);
203 }
204
205 return $data;
206 }
207
208 if (!$this->normalizers) {
209 throw new LogicException('You must register at least one normalizer to be able to denormalize objects.');
210 }
211
212 if (!$normalizer) {
213 throw new NotNormalizableValueException(\sprintf('Could not denormalize object of type "%s", no supporting normalizer found.', $type));
214 }
215
216 if ((isset($context[DenormalizerInterface::COLLECT_DENORMALIZATION_ERRORS]) || isset($this->defaultContext[DenormalizerInterface::COLLECT_DENORMALIZATION_ERRORS])) && !isset($context['not_normalizable_value_exceptions'])) {
217 unset($context[DenormalizerInterface::COLLECT_DENORMALIZATION_ERRORS]);
218 $context['not_normalizable_value_exceptions'] = [];
219 $errors = &$context['not_normalizable_value_exceptions'];
220 $denormalized = $normalizer->denormalize($data, $type, $format, $context);
221
222 if ($errors) {
223 // merge errors so that one path has only one error
224 $uniqueErrors = [];
225 foreach ($errors as $error) {
226 if (null === $error->getPath()) {
227 $uniqueErrors[] = $error;
228 continue;
229 }
230
231 $uniqueErrors[$error->getPath()] ??= $error;
232 }
233
234 throw new PartialDenormalizationException($denormalized, array_values($uniqueErrors));
235 }
236
237 return $denormalized;
238 }
239
240 return $normalizer->denormalize($data, $type, $format, $context);
241 }
242
243 public function getSupportedTypes(?string $format): array
244 {
245 return ['*' => false];
246 }
247
248 public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
249 {
250 return null !== $this->getNormalizer($data, $format, $context);
251 }
252
253 public function supportsDenormalization(mixed $data, string $type, ?string $format = null, array $context = []): bool
254 {
255 return isset(self::SCALAR_TYPES[$type]) || null !== $this->getDenormalizer($data, $type, $format, $context);
256 }
257
258 /**
259 * Returns a matching normalizer.
260 *
261 * @param mixed $data Data to get the serializer for
262 * @param string|null $format Format name, present to give the option to normalizers to act differently based on formats
263 * @param array $context Options available to the normalizer
264 */
265 private function getNormalizer(mixed $data, ?string $format, array $context): ?NormalizerInterface
266 {
267 if (\is_object($data)) {
268 $type = $data::class;
269 $genericType = 'object';
270 } else {
271 $type = 'native-'.\gettype($data);
272 $genericType = '*';
273 }
274
275 if (!isset($this->normalizerCache[$format ?? ''][$type])) {
276 $this->normalizerCache[$format ?? ''][$type] = [];
277
278 foreach ($this->normalizers as $k => $normalizer) {
279 if (!$normalizer instanceof NormalizerInterface) {
280 continue;
281 }
282
283 $supportedTypes = $normalizer->getSupportedTypes($format);
284
285 foreach ($supportedTypes as $supportedType => $isCacheable) {
286 if (\in_array($supportedType, ['*', 'object'], true)
287 || $type !== $supportedType && ('object' !== $genericType || !is_subclass_of($type, $supportedType))
288 ) {
289 continue;
290 }
291
292 if (null === $isCacheable) {
293 unset($supportedTypes['*'], $supportedTypes['object']);
294 } elseif ($this->normalizerCache[$format ?? ''][$type][$k] = $isCacheable && $normalizer->supportsNormalization($data, $format, $context)) {
295 break 2;
296 }
297
298 break;
299 }
300
301 if (null === $isCacheable = $supportedTypes[\array_key_exists($genericType, $supportedTypes) ? $genericType : '*'] ?? null) {
302 continue;
303 }
304
305 if ($this->normalizerCache[$format ?? ''][$type][$k] ??= $isCacheable && $normalizer->supportsNormalization($data, $format, $context)) {
306 break;
307 }
308 }
309 }
310
311 foreach ($this->normalizerCache[$format ?? ''][$type] as $k => $cached) {
312 $normalizer = $this->normalizers[$k];
313 if ($cached || $normalizer->supportsNormalization($data, $format, $context)) {
314 return $normalizer;
315 }
316 }
317
318 return null;
319 }
320
321 /**
322 * Returns a matching denormalizer.
323 *
324 * @param mixed $data Data to restore
325 * @param string $class The expected class to instantiate
326 * @param string|null $format Format name, present to give the option to normalizers to act differently based on formats
327 * @param array $context Options available to the denormalizer
328 */
329 private function getDenormalizer(mixed $data, string $class, ?string $format, array $context): ?DenormalizerInterface
330 {
331 if (!isset($this->denormalizerCache[$format ?? ''][$class])) {
332 $this->denormalizerCache[$format ?? ''][$class] = [];
333 $genericType = class_exists($class) || interface_exists($class, false) ? 'object' : '*';
334
335 foreach ($this->normalizers as $k => $normalizer) {
336 if (!$normalizer instanceof DenormalizerInterface) {
337 continue;
338 }
339
340 $supportedTypes = $normalizer->getSupportedTypes($format);
341
342 $doesClassRepresentCollection = str_ends_with($class, '[]');
343
344 foreach ($supportedTypes as $supportedType => $isCacheable) {
345 if (\in_array($supportedType, ['*', 'object'], true)
346 || $class !== $supportedType && ('object' !== $genericType || !is_subclass_of($class, $supportedType))
347 && !($doesClassRepresentCollection && str_ends_with($supportedType, '[]') && is_subclass_of(strstr($class, '[]', true), strstr($supportedType, '[]', true)))
348 ) {
349 continue;
350 }
351
352 if (null === $isCacheable) {
353 unset($supportedTypes['*'], $supportedTypes['object']);
354 } elseif ($this->denormalizerCache[$format ?? ''][$class][$k] = $isCacheable && $normalizer->supportsDenormalization(null, $class, $format, $context)) {
355 break 2;
356 }
357
358 break;
359 }
360
361 if (null === $isCacheable = $supportedTypes[\array_key_exists($genericType, $supportedTypes) ? $genericType : '*'] ?? null) {
362 continue;
363 }
364
365 if ($this->denormalizerCache[$format ?? ''][$class][$k] ??= $isCacheable && $normalizer->supportsDenormalization(null, $class, $format, $context)) {
366 break;
367 }
368 }
369 }
370
371 foreach ($this->denormalizerCache[$format ?? ''][$class] as $k => $cached) {
372 $normalizer = $this->normalizers[$k];
373 if ($cached || $normalizer->supportsDenormalization($data, $class, $format, $context)) {
374 return $normalizer;
375 }
376 }
377
378 return null;
379 }
380
381 final public function encode(mixed $data, string $format, array $context = []): string
382 {
383 return $this->encoder->encode($data, $format, $context);
384 }
385
386 final public function decode(string $data, string $format, array $context = []): mixed
387 {
388 return $this->decoder->decode($data, $format, $context);
389 }
390
391 public function supportsEncoding(string $format, array $context = []): bool
392 {
393 return $this->encoder->supportsEncoding($format, $context);
394 }
395
396 public function supportsDecoding(string $format, array $context = []): bool
397 {
398 return $this->decoder->supportsDecoding($format, $context);
399 }
400 }