Debian Codegraph @

lib/3rdParty/composer/symfony/serializer/Normalizer/AbstractObjectNormalizer.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\Normalizer;
13
14 use Symfony\Component\PropertyAccess\Exception\NoSuchIndexException;
15 use Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException;
16 use Symfony\Component\PropertyAccess\Exception\UninitializedPropertyException;
17 use Symfony\Component\PropertyAccess\PropertyAccess;
18 use Symfony\Component\PropertyInfo\PropertyTypeExtractorInterface;
19 use Symfony\Component\PropertyInfo\Type as LegacyType;
20 use Symfony\Component\Serializer\Encoder\CsvEncoder;
21 use Symfony\Component\Serializer\Encoder\JsonEncoder;
22 use Symfony\Component\Serializer\Encoder\XmlEncoder;
23 use Symfony\Component\Serializer\Exception\ExtraAttributesException;
24 use Symfony\Component\Serializer\Exception\InvalidArgumentException;
25 use Symfony\Component\Serializer\Exception\LogicException;
26 use Symfony\Component\Serializer\Exception\MissingConstructorArgumentsException;
27 use Symfony\Component\Serializer\Exception\NotNormalizableValueException;
28 use Symfony\Component\Serializer\Mapping\AttributeMetadata;
29 use Symfony\Component\Serializer\Mapping\AttributeMetadataInterface;
30 use Symfony\Component\Serializer\Mapping\ClassDiscriminatorFromClassMetadata;
31 use Symfony\Component\Serializer\Mapping\ClassDiscriminatorResolverInterface;
32 use Symfony\Component\Serializer\Mapping\ClassMetadataInterface;
33 use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
34 use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
35 use Symfony\Component\TypeInfo\Exception\LogicException as TypeInfoLogicException;
36 use Symfony\Component\TypeInfo\Type;
37 use Symfony\Component\TypeInfo\Type\BuiltinType;
38 use Symfony\Component\TypeInfo\Type\CollectionType;
39 use Symfony\Component\TypeInfo\Type\IntersectionType;
40 use Symfony\Component\TypeInfo\Type\NullableType;
41 use Symfony\Component\TypeInfo\Type\ObjectType;
42 use Symfony\Component\TypeInfo\Type\UnionType;
43 use Symfony\Component\TypeInfo\Type\WrappingTypeInterface;
44 use Symfony\Component\TypeInfo\TypeContext\TypeContextFactory;
45 use Symfony\Component\TypeInfo\TypeIdentifier;
46 use Symfony\Component\TypeInfo\TypeResolver\ReflectionTypeResolver;
47
48 /**
49 * Base class for a normalizer dealing with objects.
50 *
51 * @author Kévin Dunglas <[email protected]>
52 */
53 abstract class AbstractObjectNormalizer extends AbstractNormalizer
54 {
55 /**
56 * Set to true to respect the max depth metadata on fields.
57 */
58 public const ENABLE_MAX_DEPTH = 'enable_max_depth';
59
60 /**
61 * How to track the current depth in the context.
62 */
63 public const DEPTH_KEY_PATTERN = 'depth_%s::%s';
64
65 /**
66 * While denormalizing, we can verify that type matches.
67 *
68 * You can disable this by setting this flag to true.
69 */
70 public const DISABLE_TYPE_ENFORCEMENT = 'disable_type_enforcement';
71
72 /**
73 * Flag to control whether fields with the value `null` should be output
74 * when normalizing or omitted.
75 */
76 public const SKIP_NULL_VALUES = 'skip_null_values';
77
78 /**
79 * Flag to control whether uninitialized PHP>=7.4 typed class properties
80 * should be excluded when normalizing.
81 */
82 public const SKIP_UNINITIALIZED_VALUES = 'skip_uninitialized_values';
83
84 /**
85 * Callback to allow to set a value for an attribute when the max depth has
86 * been reached.
87 *
88 * If no callback is given, the attribute is skipped. If a callable is
89 * given, its return value is used (even if null).
90 *
91 * The arguments are:
92 *
93 * - mixed $attributeValue value of this field
94 * - object $object the whole object being normalized
95 * - string $attributeName name of the attribute being normalized
96 * - string $format the requested format
97 * - array $context the serialization context
98 */
99 public const MAX_DEPTH_HANDLER = 'max_depth_handler';
100
101 /**
102 * Specify which context key are not relevant to determine which attributes
103 * of an object to (de)normalize.
104 */
105 public const EXCLUDE_FROM_CACHE_KEY = 'exclude_from_cache_key';
106
107 /**
108 * Flag to tell the denormalizer to also populate existing objects on
109 * attributes of the main object.
110 *
111 * Setting this to true is only useful if you also specify the root object
112 * in OBJECT_TO_POPULATE.
113 */
114 public const DEEP_OBJECT_TO_POPULATE = 'deep_object_to_populate';
115
116 /**
117 * Flag to control whether an empty object should be kept as an object (in
118 * JSON: {}) or converted to a list (in JSON: []).
119 */
120 public const PRESERVE_EMPTY_OBJECTS = 'preserve_empty_objects';
121
122 protected ?ClassDiscriminatorResolverInterface $classDiscriminatorResolver;
123
124 /**
125 * @var array<string, Type|list<LegacyType>|false>
126 */
127 private array $typeCache = [];
128 private array $attributesCache = [];
129 private readonly \Closure $objectClassResolver;
130
131 public function __construct(
132 ?ClassMetadataFactoryInterface $classMetadataFactory = null,
133 ?NameConverterInterface $nameConverter = null,
134 private ?PropertyTypeExtractorInterface $propertyTypeExtractor = null,
135 ?ClassDiscriminatorResolverInterface $classDiscriminatorResolver = null,
136 ?callable $objectClassResolver = null,
137 array $defaultContext = [],
138 ) {
139 parent::__construct($classMetadataFactory, $nameConverter, $defaultContext);
140
141 if (isset($this->defaultContext[self::MAX_DEPTH_HANDLER]) && !\is_callable($this->defaultContext[self::MAX_DEPTH_HANDLER])) {
142 throw new InvalidArgumentException(\sprintf('The "%s" given in the default context is not callable.', self::MAX_DEPTH_HANDLER));
143 }
144
145 $this->defaultContext[self::EXCLUDE_FROM_CACHE_KEY] = array_merge($this->defaultContext[self::EXCLUDE_FROM_CACHE_KEY] ?? [], [self::CIRCULAR_REFERENCE_LIMIT_COUNTERS]);
146
147 if ($classMetadataFactory) {
148 $classDiscriminatorResolver ??= new ClassDiscriminatorFromClassMetadata($classMetadataFactory);
149 }
150 $this->classDiscriminatorResolver = $classDiscriminatorResolver;
151 $this->objectClassResolver = ($objectClassResolver ?? 'get_class')(...);
152 }
153
154 public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
155 {
156 return \is_object($data) && !$data instanceof \Traversable;
157 }
158
159 public function normalize(mixed $data, ?string $format = null, array $context = []): array|string|int|float|bool|\ArrayObject|null
160 {
161 $context['_read_attributes'] = true;
162
163 if (!isset($context['cache_key'])) {
164 $context['cache_key'] = $this->getCacheKey($format, $context);
165 }
166
167 $this->validateCallbackContext($context);
168
169 if ($this->isCircularReference($data, $context)) {
170 return $this->handleCircularReference($data, $format, $context);
171 }
172
173 $normalizedData = [];
174 $stack = [];
175 $attributes = $this->getAttributes($data, $format, $context);
176 $class = ($this->objectClassResolver)($data);
177 $classMetadata = $this->classMetadataFactory?->getMetadataFor($class);
178 $attributesMetadata = $this->classMetadataFactory?->getMetadataFor($class)->getAttributesMetadata();
179 if (isset($context[self::MAX_DEPTH_HANDLER])) {
180 $maxDepthHandler = $context[self::MAX_DEPTH_HANDLER];
181 if (!\is_callable($maxDepthHandler)) {
182 throw new InvalidArgumentException(\sprintf('The "%s" given in the context is not callable.', self::MAX_DEPTH_HANDLER));
183 }
184 } else {
185 $maxDepthHandler = null;
186 }
187
188 foreach ($attributes as $attribute) {
189 $maxDepthReached = false;
190 if (null !== $attributesMetadata && ($maxDepthReached = $this->isMaxDepthReached($attributesMetadata, $class, $attribute, $context)) && !$maxDepthHandler) {
191 continue;
192 }
193
194 $attributeContext = $this->getAttributeNormalizationContext($data, $attribute, $context);
195
196 try {
197 $attributeValue = $attribute === $this->classDiscriminatorResolver?->getMappingForMappedObject($data)?->getTypeProperty()
198 ? $this->classDiscriminatorResolver?->getTypeForMappedObject($data)
199 : $this->getAttributeValue($data, $attribute, $format, $attributeContext);
200 } catch (UninitializedPropertyException $e) {
201 if ($context[self::SKIP_UNINITIALIZED_VALUES] ?? $this->defaultContext[self::SKIP_UNINITIALIZED_VALUES] ?? true) {
202 continue;
203 }
204 throw $e;
205 }
206
207 if ($maxDepthReached) {
208 $attributeValue = $maxDepthHandler($attributeValue, $data, $attribute, $format, $attributeContext);
209 }
210
211 $stack[$attribute] = $this->applyCallbacks($attributeValue, $data, $attribute, $format, $attributeContext);
212 }
213
214 foreach ($stack as $attribute => $attributeValue) {
215 $attributeContext = $this->getAttributeNormalizationContext($data, $attribute, $context);
216
217 if (!$this->serializer instanceof NormalizerInterface) {
218 if (null === $attributeValue || \is_scalar($attributeValue)) {
219 $normalizedData = $this->updateData($normalizedData, $attribute, $attributeValue, $class, $format, $attributeContext, $attributesMetadata, $classMetadata);
220 continue;
221 }
222 throw new LogicException(\sprintf('Cannot normalize attribute "%s" because the injected serializer is not a normalizer.', $attribute));
223 }
224
225 $childContext = $this->createChildContext($attributeContext, $attribute, $format);
226
227 $normalizedData = $this->updateData($normalizedData, $attribute, $this->serializer->normalize($attributeValue, $format, $childContext), $class, $format, $attributeContext, $attributesMetadata, $classMetadata);
228 }
229
230 $preserveEmptyObjects = $context[self::PRESERVE_EMPTY_OBJECTS] ?? $this->defaultContext[self::PRESERVE_EMPTY_OBJECTS] ?? false;
231 if ($preserveEmptyObjects && !$normalizedData) {
232 return new \ArrayObject();
233 }
234
235 return $normalizedData;
236 }
237
238 protected function instantiateObject(array &$data, string $class, array &$context, \ReflectionClass $reflectionClass, array|bool $allowedAttributes, ?string $format = null): object
239 {
240 if ($class !== $mappedClass = $this->getMappedClass($data, $class, $context)) {
241 return $this->instantiateObject($data, $mappedClass, $context, new \ReflectionClass($mappedClass), $allowedAttributes, $format);
242 }
243
244 return parent::instantiateObject($data, $class, $context, $reflectionClass, $allowedAttributes, $format);
245 }
246
247 /**
248 * Gets and caches attributes for the given object, format and context.
249 *
250 * @return string[]
251 */
252 protected function getAttributes(object $object, ?string $format, array $context): array
253 {
254 $class = ($this->objectClassResolver)($object);
255 $key = $class.'-'.$context['cache_key'];
256
257 if (isset($this->attributesCache[$key])) {
258 return $this->attributesCache[$key];
259 }
260
261 $allowedAttributes = $this->getAllowedAttributes($object, $context, true);
262
263 if (false !== $allowedAttributes) {
264 if ($context['cache_key']) {
265 $this->attributesCache[$key] = $allowedAttributes;
266 }
267
268 return $allowedAttributes;
269 }
270
271 $attributes = $this->extractAttributes($object, $format, $context);
272
273 if ($mapping = $this->classDiscriminatorResolver?->getMappingForMappedObject($object)) {
274 array_unshift($attributes, $mapping->getTypeProperty());
275 }
276
277 if ($context['cache_key'] && \stdClass::class !== $class) {
278 $this->attributesCache[$key] = $attributes;
279 }
280
281 return $attributes;
282 }
283
284 /**
285 * Extracts attributes to normalize from the class of the given object, format and context.
286 *
287 * @return string[]
288 */
289 abstract protected function extractAttributes(object $object, ?string $format = null, array $context = []): array;
290
291 /**
292 * Gets the attribute value.
293 *
294 * @throws UninitializedPropertyException When the attribute exists but is not initialized on the object
295 */
296 abstract protected function getAttributeValue(object $object, string $attribute, ?string $format = null, array $context = []): mixed;
297
298 public function supportsDenormalization(mixed $data, string $type, ?string $format = null, array $context = []): bool
299 {
300 return class_exists($type) || (interface_exists($type, false) && null !== $this->classDiscriminatorResolver?->getMappingForClass($type));
301 }
302
303 public function denormalize(mixed $data, string $type, ?string $format = null, array $context = []): mixed
304 {
305 $context['_read_attributes'] = false;
306
307 if (!isset($context['cache_key'])) {
308 $context['cache_key'] = $this->getCacheKey($format, $context);
309 }
310
311 $this->validateCallbackContext($context);
312
313 if (null === $data && isset($context['value_type']) && ($context['value_type'] instanceof Type || $context['value_type'] instanceof LegacyType) && $context['value_type']->isNullable()) {
314 return null;
315 }
316
317 if (XmlEncoder::FORMAT === $format && !\is_array($data)) {
318 $data = ['#' => $data];
319 }
320
321 $allowedAttributes = $this->getAllowedAttributes($type, $context, true);
322 $normalizedData = $this->prepareForDenormalization($data);
323 $extraAttributes = [];
324
325 $mappedClass = $this->getMappedClass($normalizedData, $type, $context);
326
327 $nestedAttributes = $this->getNestedAttributes($mappedClass);
328 $nestedData = $originalNestedData = [];
329 $propertyAccessor = PropertyAccess::createPropertyAccessorBuilder()->enableExceptionOnInvalidIndex()->getPropertyAccessor();
330 foreach ($nestedAttributes as $property => $serializedPath) {
331 try {
332 $value = $propertyAccessor->getValue($normalizedData, $serializedPath);
333 $convertedProperty = $this->nameConverter ? $this->nameConverter->normalize($property, $mappedClass, $format, $context) : $property;
334 $nestedData[$convertedProperty] = $value;
335 $originalNestedData[$property] = $value;
336 $normalizedData = $this->removeNestedValue($serializedPath->getElements(), $normalizedData);
337 } catch (NoSuchIndexException) {
338 }
339 }
340
341 $normalizedData = $nestedData + $normalizedData;
342
343 $object = $this->instantiateObject($normalizedData, $mappedClass, $context, new \ReflectionClass($mappedClass), $allowedAttributes, $format);
344 $resolvedClass = ($this->objectClassResolver)($object);
345
346 foreach ($normalizedData as $attribute => $value) {
347 if ($this->nameConverter) {
348 $notConverted = $attribute;
349 $attribute = $this->nameConverter->denormalize($attribute, $resolvedClass, $format, $context);
350 if (isset($nestedData[$notConverted]) && !isset($originalNestedData[$attribute])) {
351 throw new LogicException(\sprintf('Duplicate values for key "%s" found. One value is set via the SerializedPath attribute: "%s", the other one is set via the SerializedName attribute: "%s".', $notConverted, implode('->', $nestedAttributes[$notConverted]->getElements()), $attribute));
352 }
353
354 if ($attribute === $notConverted
355 && !($context[self::ALLOW_EXTRA_ATTRIBUTES] ?? $this->defaultContext[self::ALLOW_EXTRA_ATTRIBUTES])
356 && (false === $allowedAttributes || \in_array($attribute, $allowedAttributes, true))
357 && $this->nameConverter->normalize($attribute, $resolvedClass, $format, $context) !== $attribute
358 ) {
359 // Input was in wrong format (e.g., camelCase when snake_case expected)
360 $extraAttributes[] = $notConverted;
361 continue;
362 }
363 }
364
365 $attributeContext = $this->getAttributeDenormalizationContext($resolvedClass, $attribute, $context);
366
367 if ((false !== $allowedAttributes && !\in_array($attribute, $allowedAttributes, true)) || !$this->isAllowedAttribute($resolvedClass, $attribute, $format, $context)) {
368 if (!($context[self::ALLOW_EXTRA_ATTRIBUTES] ?? $this->defaultContext[self::ALLOW_EXTRA_ATTRIBUTES])) {
369 $extraAttributes[] = $attribute;
370 }
371
372 continue;
373 }
374
375 if ($attributeContext[self::DEEP_OBJECT_TO_POPULATE] ?? $this->defaultContext[self::DEEP_OBJECT_TO_POPULATE] ?? false) {
376 $discriminatorMapping = $this->classDiscriminatorResolver?->getMappingForMappedObject($object);
377
378 try {
379 $attributeContext[self::OBJECT_TO_POPULATE] = $attribute === $discriminatorMapping?->getTypeProperty()
380 ? $discriminatorMapping
381 : $this->getAttributeValue($object, $attribute, $format, $attributeContext);
382 } catch (NoSuchPropertyException) {
383 } catch (UninitializedPropertyException $e) {
384 if (!($context[self::SKIP_UNINITIALIZED_VALUES] ?? $this->defaultContext[self::SKIP_UNINITIALIZED_VALUES] ?? true)) {
385 throw $e;
386 }
387 }
388 }
389
390 if (null !== $type = $this->getType($resolvedClass, $attribute)) {
391 try {
392 // BC layer for PropertyTypeExtractorInterface::getTypes().
393 // Can be removed as soon as PropertyTypeExtractorInterface::getTypes() is removed (8.0).
394 if (\is_array($type)) {
395 $value = $this->validateAndDenormalizeLegacy($type, $resolvedClass, $attribute, $value, $format, $attributeContext);
396 } else {
397 $value = $this->validateAndDenormalize($type, $resolvedClass, $attribute, $value, $format, $attributeContext);
398 }
399 } catch (NotNormalizableValueException $exception) {
400 if (isset($context['not_normalizable_value_exceptions'])) {
401 $context['not_normalizable_value_exceptions'][] = $exception;
402 continue;
403 }
404 throw $exception;
405 }
406 }
407
408 $value = $this->applyCallbacks($value, $resolvedClass, $attribute, $format, $attributeContext);
409
410 try {
411 $this->setAttributeValue($object, $attribute, $value, $format, $attributeContext);
412 } catch (NotNormalizableValueException $exception) {
413 if (isset($context['not_normalizable_value_exceptions'])) {
414 $context['not_normalizable_value_exceptions'][] = $exception;
415 continue;
416 }
417 throw $exception;
418 }
419 }
420
421 if ($extraAttributes) {
422 throw new ExtraAttributesException($extraAttributes);
423 }
424
425 return $object;
426 }
427
428 /**
429 * @throws NotNormalizableValueException When the value cannot be assigned to the attribute (e.g. type mismatch)
430 */
431 abstract protected function setAttributeValue(object $object, string $attribute, mixed $value, ?string $format = null, array $context = []): void;
432
433 /**
434 * Validates the submitted data and denormalizes it.
435 *
436 * BC layer for PropertyTypeExtractorInterface::getTypes().
437 * Can be removed as soon as PropertyTypeExtractorInterface::getTypes() is removed (8.0).
438 *
439 * @param LegacyType[] $types
440 *
441 * @throws NotNormalizableValueException
442 * @throws ExtraAttributesException
443 * @throws MissingConstructorArgumentsException
444 * @throws LogicException
445 */
446 private function validateAndDenormalizeLegacy(array $types, string $currentClass, string $attribute, mixed $data, ?string $format, array $context): mixed
447 {
448 $expectedTypes = [];
449 $isUnionType = \count($types) > 1;
450 $e = null;
451 $extraAttributesException = null;
452 $missingConstructorArgumentsException = null;
453 $isNullable = false;
454 foreach ($types as $type) {
455 if (null === $data && $type->isNullable()) {
456 return null;
457 }
458
459 $collectionValueType = $type->isCollection() ? $type->getCollectionValueTypes()[0] ?? null : null;
460
461 // Fix a collection that contains the only one element
462 // This is special to xml format only
463 if ('xml' === $format && null !== $collectionValueType && (!\is_array($data) || !\is_int(key($data)))) {
464 $data = [$data];
465 }
466
467 // This try-catch should cover all NotNormalizableValueException (and all return branches after the first
468 // exception) so we could try denormalizing all types of an union type. If the target type is not an union
469 // type, we will just re-throw the caught exception.
470 // In the case of no denormalization succeeds with an union type, it will fall back to the default exception
471 // with the acceptable types list.
472 try {
473 // In XML and CSV all basic datatypes are represented as strings, it is e.g. not possible to determine,
474 // if a value is meant to be a string, float, int or a boolean value from the serialized representation.
475 // That's why we have to transform the values, if one of these non-string basic datatypes is expected.
476 $builtinType = $type->getBuiltinType();
477 if (\is_string($data) && (XmlEncoder::FORMAT === $format || CsvEncoder::FORMAT === $format)) {
478 if ('' === $data) {
479 if (LegacyType::BUILTIN_TYPE_ARRAY === $builtinType) {
480 return [];
481 }
482
483 if (LegacyType::BUILTIN_TYPE_STRING === $builtinType) {
484 return '';
485 }
486
487 // Don't return null yet because Object-types that come first may accept empty-string too
488 $isNullable = $isNullable ?: $type->isNullable();
489 }
490
491 switch ($builtinType) {
492 case LegacyType::BUILTIN_TYPE_BOOL:
493 // according to https://www.w3.org/TR/xmlschema-2/#boolean, valid representations are "false", "true", "0" and "1"
494 if ('false' === $data || '0' === $data) {
495 $data = false;
496 } elseif ('true' === $data || '1' === $data) {
497 $data = true;
498 } else {
499 throw NotNormalizableValueException::createForUnexpectedDataType(\sprintf('The type of the "%s" attribute for class "%s" must be bool ("%s" given).', $attribute, $currentClass, $data), $data, [LegacyType::BUILTIN_TYPE_BOOL], $context['deserialization_path'] ?? null);
500 }
501 break;
502 case LegacyType::BUILTIN_TYPE_INT:
503 if (ctype_digit(isset($data[0]) && '-' === $data[0] ? substr($data, 1) : $data)) {
504 $data = (int) $data;
505 } else {
506 throw NotNormalizableValueException::createForUnexpectedDataType(\sprintf('The type of the "%s" attribute for class "%s" must be int ("%s" given).', $attribute, $currentClass, $data), $data, [LegacyType::BUILTIN_TYPE_INT], $context['deserialization_path'] ?? null);
507 }
508 break;
509 case LegacyType::BUILTIN_TYPE_FLOAT:
510 if (is_numeric($data)) {
511 return (float) $data;
512 }
513
514 return match ($data) {
515 'NaN' => \NAN,
516 'INF' => \INF,
517 '-INF' => -\INF,
518 default => throw NotNormalizableValueException::createForUnexpectedDataType(\sprintf('The type of the "%s" attribute for class "%s" must be float ("%s" given).', $attribute, $currentClass, $data), $data, [LegacyType::BUILTIN_TYPE_FLOAT], $context['deserialization_path'] ?? null),
519 };
520 }
521 }
522
523 if (is_numeric($data) && XmlEncoder::FORMAT === $format) {
524 // encoder parsed them wrong, so they might need to be transformed back
525 switch ($builtinType) {
526 case LegacyType::BUILTIN_TYPE_STRING:
527 return (string) $data;
528 case LegacyType::BUILTIN_TYPE_FLOAT:
529 return (float) $data;
530 case LegacyType::BUILTIN_TYPE_INT:
531 return (int) $data;
532 }
533 }
534
535 if (null !== $collectionValueType && LegacyType::BUILTIN_TYPE_OBJECT === $collectionValueType->getBuiltinType()) {
536 $builtinType = LegacyType::BUILTIN_TYPE_OBJECT;
537 $class = $collectionValueType->getClassName().'[]';
538
539 if ($collectionKeyType = $type->getCollectionKeyTypes()) {
540 $context['key_type'] = \count($collectionKeyType) > 1 ? $collectionKeyType : $collectionKeyType[0];
541 }
542
543 $context['value_type'] = $collectionValueType;
544 } elseif ($type->isCollection() && ($collectionValueType = $type->getCollectionValueTypes()) && LegacyType::BUILTIN_TYPE_ARRAY === $collectionValueType[0]->getBuiltinType()) {
545 // get inner type for any nested array
546 [$innerType] = $collectionValueType;
547
548 // note that it will break for any other builtinType
549 $dimensions = '[]';
550 while ($innerType->getCollectionValueTypes() && LegacyType::BUILTIN_TYPE_ARRAY === $innerType->getBuiltinType()) {
551 $dimensions .= '[]';
552 [$innerType] = $innerType->getCollectionValueTypes();
553 }
554
555 if (null !== $innerType->getClassName()) {
556 // the builtinType is the inner one and the class is the class followed by []...[]
557 $builtinType = $innerType->getBuiltinType();
558 $class = $innerType->getClassName().$dimensions;
559
560 if ($collectionKeyType = $type->getCollectionKeyTypes()) {
561 $context['key_type'] = \count($collectionKeyType) > 1 ? $collectionKeyType : $collectionKeyType[0];
562 }
563
564 $context['value_type'] = $collectionValueType[0];
565 } else {
566 // default fallback (keep it as array)
567 $builtinType = $type->getBuiltinType();
568 $class = $type->getClassName();
569 }
570 } else {
571 $builtinType = $type->getBuiltinType();
572 $class = $type->getClassName();
573 }
574
575 $expectedTypes[LegacyType::BUILTIN_TYPE_OBJECT === $builtinType && $class ? $class : $builtinType] = true;
576
577 if (LegacyType::BUILTIN_TYPE_OBJECT === $builtinType && null !== $class) {
578 if (!$this->serializer instanceof DenormalizerInterface) {
579 throw new LogicException(\sprintf('Cannot denormalize attribute "%s" for class "%s" because injected serializer is not a denormalizer.', $attribute, $class));
580 }
581
582 $childContext = $this->createChildContext($context, $attribute, $format);
583 if ($this->serializer->supportsDenormalization($data, $class, $format, $childContext)) {
584 return $this->serializer->denormalize($data, $class, $format, $childContext);
585 }
586 }
587
588 // JSON only has a Number type corresponding to both int and float PHP types.
589 // PHP's json_encode, JavaScript's JSON.stringify, Go's json.Marshal as well as most other JSON encoders convert
590 // floating-point numbers like 12.0 to 12 (the decimal part is dropped when possible).
591 // PHP's json_decode automatically converts Numbers without a decimal part to integers.
592 // To circumvent this behavior, integers are converted to floats when denormalizing JSON based formats and when
593 // a float is expected.
594 if (LegacyType::BUILTIN_TYPE_FLOAT === $builtinType && \is_int($data) && null !== $format && str_contains($format, JsonEncoder::FORMAT)) {
595 return (float) $data;
596 }
597
598 if (LegacyType::BUILTIN_TYPE_BOOL === $builtinType && (\is_string($data) || \is_int($data)) && ($context[self::FILTER_BOOL] ?? false)) {
599 return filter_var($data, \FILTER_VALIDATE_BOOL, \FILTER_NULL_ON_FAILURE);
600 }
601
602 if ((LegacyType::BUILTIN_TYPE_FALSE === $builtinType && false === $data) || (LegacyType::BUILTIN_TYPE_TRUE === $builtinType && true === $data)) {
603 return $data;
604 }
605
606 switch ($builtinType) {
607 case LegacyType::BUILTIN_TYPE_ARRAY:
608 case LegacyType::BUILTIN_TYPE_BOOL:
609 case LegacyType::BUILTIN_TYPE_CALLABLE:
610 case LegacyType::BUILTIN_TYPE_FLOAT:
611 case LegacyType::BUILTIN_TYPE_INT:
612 case LegacyType::BUILTIN_TYPE_ITERABLE:
613 case LegacyType::BUILTIN_TYPE_NULL:
614 case LegacyType::BUILTIN_TYPE_OBJECT:
615 case LegacyType::BUILTIN_TYPE_RESOURCE:
616 case LegacyType::BUILTIN_TYPE_STRING:
617 if (('is_'.$builtinType)($data)) {
618 return $data;
619 }
620
621 break;
622 }
623 } catch (NotNormalizableValueException|InvalidArgumentException $e) {
624 if (!$isUnionType && !$isNullable) {
625 throw $e;
626 }
627
628 $expectedTypes[LegacyType::BUILTIN_TYPE_OBJECT === $builtinType && $class ? $class : $builtinType] = true;
629 } catch (ExtraAttributesException $e) {
630 if (!$isUnionType && !$isNullable) {
631 throw $e;
632 }
633
634 $extraAttributesException ??= $e;
635 } catch (MissingConstructorArgumentsException $e) {
636 if (!$isUnionType && !$isNullable) {
637 throw $e;
638 }
639
640 $missingConstructorArgumentsException ??= $e;
641 }
642 }
643
644 if ($isNullable) {
645 return null;
646 }
647
648 if ($extraAttributesException) {
649 throw $extraAttributesException;
650 }
651
652 if ($missingConstructorArgumentsException) {
653 throw $missingConstructorArgumentsException;
654 }
655
656 if (!$isUnionType && $e) {
657 throw $e;
658 }
659
660 if ($context[self::DISABLE_TYPE_ENFORCEMENT] ?? $this->defaultContext[self::DISABLE_TYPE_ENFORCEMENT] ?? false) {
661 return $data;
662 }
663
664 throw NotNormalizableValueException::createForUnexpectedDataType(\sprintf('The type of the "%s" attribute for class "%s" must be one of "%s" ("%s" given).', $attribute, $currentClass, implode('", "', array_keys($expectedTypes)), get_debug_type($data)), $data, array_keys($expectedTypes), $context['deserialization_path'] ?? $attribute);
665 }
666
667 /**
668 * Validates the submitted data and denormalizes it.
669 *
670 * @throws NotNormalizableValueException
671 * @throws ExtraAttributesException
672 * @throws MissingConstructorArgumentsException
673 * @throws LogicException
674 */
675 private function validateAndDenormalize(Type $type, string $currentClass, string $attribute, mixed $data, ?string $format, array $context): mixed
676 {
677 $expectedTypes = [];
678
679 // BC layer for type-info < 7.2
680 if (method_exists(Type::class, 'asNonNullable')) {
681 $isUnionType = $type->asNonNullable() instanceof UnionType;
682 } else {
683 $isUnionType = $type instanceof UnionType;
684 }
685
686 $e = null;
687 $extraAttributesException = null;
688 $missingConstructorArgumentsException = null;
689
690 $types = match (true) {
691 $type instanceof IntersectionType => throw new LogicException('Unable to handle intersection type.'),
692 $type instanceof UnionType => $type->getTypes(),
693 default => [$type],
694 };
695
696 foreach ($types as $t) {
697 if (null === $data && $type->isNullable()) {
698 return null;
699 }
700
701 $collectionKeyType = $collectionValueType = null;
702 if ($t instanceof CollectionType) {
703 $collectionKeyType = $t->getCollectionKeyType();
704 $collectionValueType = $t->getCollectionValueType();
705 }
706
707 // BC layer for type-info < 7.2
708 if (method_exists(Type::class, 'getBaseType')) {
709 $t = $t->getBaseType();
710 } else {
711 while ($t instanceof WrappingTypeInterface) {
712 $t = $t->getWrappedType();
713 }
714 }
715
716 // Fix a collection that contains the only one element
717 // This is special to xml format only
718 if ('xml' === $format && $collectionValueType && (!\is_array($data) || !\is_int(key($data)))) {
719 // BC layer for type-info < 7.2
720 $isMixedType = method_exists(Type::class, 'isA') ? $collectionValueType->isA(TypeIdentifier::MIXED) : $collectionValueType->isIdentifiedBy(TypeIdentifier::MIXED);
721 if (!$isMixedType) {
722 $data = [$data];
723 }
724 }
725
726 // This try-catch should cover all NotNormalizableValueException (and all return branches after the first
727 // exception) so we could try denormalizing all types of an union type. If the target type is not an union
728 // type, we will just re-throw the caught exception.
729 // In the case of no denormalization succeeds with an union type, it will fall back to the default exception
730 // with the acceptable types list.
731 try {
732 // In XML and CSV all basic datatypes are represented as strings, it is e.g. not possible to determine,
733 // if a value is meant to be a string, float, int or a boolean value from the serialized representation.
734 // That's why we have to transform the values, if one of these non-string basic datatypes is expected.
735 $typeIdentifier = $t->getTypeIdentifier();
736 if (\is_string($data) && (XmlEncoder::FORMAT === $format || CsvEncoder::FORMAT === $format)) {
737 if ('' === $data) {
738 if (TypeIdentifier::ARRAY === $typeIdentifier) {
739 return [];
740 }
741
742 if (TypeIdentifier::STRING === $typeIdentifier) {
743 return '';
744 }
745 }
746
747 switch ($typeIdentifier) {
748 case TypeIdentifier::BOOL:
749 // according to https://www.w3.org/TR/xmlschema-2/#boolean, valid representations are "false", "true", "0" and "1"
750 if ('false' === $data || '0' === $data) {
751 $data = false;
752 } elseif ('true' === $data || '1' === $data) {
753 $data = true;
754 } else {
755 throw NotNormalizableValueException::createForUnexpectedDataType(\sprintf('The type of the "%s" attribute for class "%s" must be bool ("%s" given).', $attribute, $currentClass, $data), $data, [Type::bool()], $context['deserialization_path'] ?? null);
756 }
757 break;
758 case TypeIdentifier::INT:
759 if (ctype_digit(isset($data[0]) && '-' === $data[0] ? substr($data, 1) : $data)) {
760 $data = (int) $data;
761 } else {
762 throw NotNormalizableValueException::createForUnexpectedDataType(\sprintf('The type of the "%s" attribute for class "%s" must be int ("%s" given).', $attribute, $currentClass, $data), $data, [Type::int()], $context['deserialization_path'] ?? null);
763 }
764 break;
765 case TypeIdentifier::FLOAT:
766 if (is_numeric($data)) {
767 return (float) $data;
768 }
769
770 return match ($data) {
771 'NaN' => \NAN,
772 'INF' => \INF,
773 '-INF' => -\INF,
774 default => throw NotNormalizableValueException::createForUnexpectedDataType(\sprintf('The type of the "%s" attribute for class "%s" must be float ("%s" given).', $attribute, $currentClass, $data), $data, [Type::float()], $context['deserialization_path'] ?? null),
775 };
776 }
777 }
778
779 if (is_numeric($data) && XmlEncoder::FORMAT === $format) {
780 // encoder parsed them wrong, so they might need to be transformed back
781 switch ($typeIdentifier) {
782 case TypeIdentifier::STRING:
783 return (string) $data;
784 case TypeIdentifier::FLOAT:
785 return (float) $data;
786 case TypeIdentifier::INT:
787 return (int) $data;
788 }
789 }
790
791 if ($collectionValueType) {
792 try {
793 $collectionValueBaseType = $collectionValueType;
794
795 // BC layer for type-info < 7.2
796 if (!interface_exists(WrappingTypeInterface::class)) {
797 $collectionValueBaseType = $collectionValueType->getBaseType();
798 } else {
799 while ($collectionValueBaseType instanceof WrappingTypeInterface) {
800 $collectionValueBaseType = $collectionValueBaseType->getWrappedType();
801 }
802 }
803 } catch (TypeInfoLogicException) {
804 $collectionValueBaseType = Type::mixed();
805 }
806
807 if ($collectionValueBaseType instanceof ObjectType) {
808 $typeIdentifier = TypeIdentifier::OBJECT;
809 $class = $collectionValueBaseType->getClassName().'[]';
810 $context['key_type'] = $collectionKeyType;
811 $context['value_type'] = $collectionValueType;
812 } elseif (
813 // BC layer for type-info < 7.2
814 !class_exists(NullableType::class) && TypeIdentifier::ARRAY === $collectionValueBaseType->getTypeIdentifier()
815 || $collectionValueBaseType instanceof BuiltinType && TypeIdentifier::ARRAY === $collectionValueBaseType->getTypeIdentifier()
816 ) {
817 // get inner type for any nested array
818 $innerType = $collectionValueType;
819 if ($innerType instanceof NullableType) {
820 $innerType = $innerType->getWrappedType();
821 }
822
823 // note that it will break for any other builtinType
824 $dimensions = '[]';
825 while ($innerType instanceof CollectionType) {
826 $dimensions .= '[]';
827 $innerType = $innerType->getCollectionValueType();
828 if ($innerType instanceof NullableType) {
829 $innerType = $innerType->getWrappedType();
830 }
831 }
832
833 while ($innerType instanceof WrappingTypeInterface) {
834 $innerType = $innerType->getWrappedType();
835 }
836
837 if ($innerType instanceof ObjectType) {
838 // the builtinType is the inner one and the class is the class followed by []...[]
839 $typeIdentifier = TypeIdentifier::OBJECT;
840 $class = $innerType->getClassName().$dimensions;
841 $context['key_type'] = $collectionKeyType;
842 $context['value_type'] = $collectionValueType;
843 } else {
844 // default fallback (keep it as array)
845 if ($t instanceof ObjectType) {
846 $typeIdentifier = TypeIdentifier::OBJECT;
847 $class = $t->getClassName();
848 } else {
849 $typeIdentifier = $t->getTypeIdentifier();
850 $class = null;
851 }
852 }
853 } elseif ($t instanceof ObjectType) {
854 $typeIdentifier = TypeIdentifier::OBJECT;
855 $class = $t->getClassName();
856 } else {
857 $typeIdentifier = $t->getTypeIdentifier();
858 $class = null;
859 }
860 } else {
861 if ($t instanceof ObjectType) {
862 $typeIdentifier = TypeIdentifier::OBJECT;
863 $class = $t->getClassName();
864 } else {
865 $typeIdentifier = $t->getTypeIdentifier();
866 $class = null;
867 }
868 }
869
870 $expectedTypes[TypeIdentifier::OBJECT === $typeIdentifier && $class ? $class : $typeIdentifier->value] = true;
871
872 if (TypeIdentifier::OBJECT === $typeIdentifier && null !== $class) {
873 if (!$this->serializer instanceof DenormalizerInterface) {
874 throw new LogicException(\sprintf('Cannot denormalize attribute "%s" for class "%s" because injected serializer is not a denormalizer.', $attribute, $class));
875 }
876
877 $childContext = $this->createChildContext($context, $attribute, $format);
878 if ($this->serializer->supportsDenormalization($data, $class, $format, $childContext)) {
879 return $this->serializer->denormalize($data, $class, $format, $childContext);
880 }
881 }
882
883 // JSON only has a Number type corresponding to both int and float PHP types.
884 // PHP's json_encode, JavaScript's JSON.stringify, Go's json.Marshal as well as most other JSON encoders convert
885 // floating-point numbers like 12.0 to 12 (the decimal part is dropped when possible).
886 // PHP's json_decode automatically converts Numbers without a decimal part to integers.
887 // To circumvent this behavior, integers are converted to floats when denormalizing JSON based formats and when
888 // a float is expected.
889 if (TypeIdentifier::FLOAT === $typeIdentifier && \is_int($data) && null !== $format && str_contains($format, JsonEncoder::FORMAT)) {
890 return (float) $data;
891 }
892
893 if (TypeIdentifier::BOOL === $typeIdentifier && (\is_string($data) || \is_int($data)) && ($context[self::FILTER_BOOL] ?? false)) {
894 return filter_var($data, \FILTER_VALIDATE_BOOL, \FILTER_NULL_ON_FAILURE);
895 }
896
897 $dataMatchesExpectedType = match ($typeIdentifier) {
898 TypeIdentifier::ARRAY => \is_array($data),
899 TypeIdentifier::BOOL => \is_bool($data),
900 TypeIdentifier::CALLABLE => \is_callable($data),
901 TypeIdentifier::FALSE => false === $data,
902 TypeIdentifier::FLOAT => \is_float($data),
903 TypeIdentifier::INT => \is_int($data),
904 TypeIdentifier::ITERABLE => is_iterable($data),
905 TypeIdentifier::MIXED => true,
906 TypeIdentifier::NULL => null === $data,
907 TypeIdentifier::OBJECT => \is_object($data),
908 TypeIdentifier::RESOURCE => \is_resource($data),
909 TypeIdentifier::STRING => \is_string($data),
910 TypeIdentifier::TRUE => true === $data,
911 default => false,
912 };
913
914 if ($dataMatchesExpectedType) {
915 return $data;
916 }
917 } catch (NotNormalizableValueException|InvalidArgumentException $e) {
918 if (!$type instanceof UnionType) {
919 throw $e;
920 }
921
922 $expectedTypes[TypeIdentifier::OBJECT === $typeIdentifier && $class ? $class : $typeIdentifier->value] = true;
923 } catch (ExtraAttributesException $e) {
924 if (!$type instanceof UnionType) {
925 throw $e;
926 }
927
928 $extraAttributesException ??= $e;
929 } catch (MissingConstructorArgumentsException $e) {
930 if (!$type instanceof UnionType) {
931 throw $e;
932 }
933
934 $missingConstructorArgumentsException ??= $e;
935 }
936 }
937
938 if ('' === $data && (XmlEncoder::FORMAT === $format || CsvEncoder::FORMAT === $format) && $type->isNullable()) {
939 return null;
940 }
941
942 if ($extraAttributesException) {
943 throw $extraAttributesException;
944 }
945
946 if ($missingConstructorArgumentsException) {
947 throw $missingConstructorArgumentsException;
948 }
949
950 // BC layer for type-info < 7.2
951 if (!class_exists(NullableType::class)) {
952 if (!$isUnionType && $e) {
953 throw $e;
954 }
955 } else {
956 if ($e && !($type instanceof UnionType && !$type instanceof NullableType)) {
957 throw $e;
958 }
959 }
960
961 if ($context[self::DISABLE_TYPE_ENFORCEMENT] ?? $this->defaultContext[self::DISABLE_TYPE_ENFORCEMENT] ?? false) {
962 return $data;
963 }
964
965 throw NotNormalizableValueException::createForUnexpectedDataType(\sprintf('The type of the "%s" attribute for class "%s" must be one of "%s" ("%s" given).', $attribute, $currentClass, implode('", "', array_keys($expectedTypes)), get_debug_type($data)), $data, array_keys($expectedTypes), $context['deserialization_path'] ?? $attribute);
966 }
967
968 /**
969 * @internal
970 */
971 protected function denormalizeParameter(\ReflectionClass $class, \ReflectionParameter $parameter, string $parameterName, mixed $parameterData, array $context, ?string $format = null): mixed
972 {
973 if ($parameter->isVariadic() || null === $this->propertyTypeExtractor || null === $type = $this->getType($class->getName(), $parameterName)) {
974 return parent::denormalizeParameter($class, $parameter, $parameterName, $parameterData, $context, $format);
975 }
976
977 // BC layer for PropertyTypeExtractorInterface::getTypes().
978 // Can be removed as soon as PropertyTypeExtractorInterface::getTypes() is removed (8.0).
979 if (\is_array($type)) {
980 if (($parameterType = $parameter->getType()) instanceof \ReflectionNamedType && 'mixed' !== $parameterType->getName()) {
981 $matches = false;
982
983 if ($parameterType->isBuiltin()) {
984 foreach ($type as $legacyType) {
985 if ($parameterType->getName() === $legacyType->getBuiltinType()) {
986 $matches = true;
987 break;
988 }
989 }
990
991 if (!$matches) {
992 $type = [new LegacyType($parameterType->getName(), $parameter->allowsNull())];
993 }
994 } else {
995 $parameterTypeName = match ($parameterType->getName()) {
996 'self' => $parameter->getDeclaringClass()?->name ?? $class->name,
997 'parent' => $parameter->getDeclaringClass()?->getParentClass()?->name ?? $parameterType->getName(),
998 'static' => $class->name,
999 default => $parameterType->getName(),
1000 };
1001
1002 foreach ($type as $legacyType) {
1003 if (LegacyType::BUILTIN_TYPE_OBJECT === $legacyType->getBuiltinType() && $parameterTypeName === $legacyType->getClassName()) {
1004 $matches = true;
1005 break;
1006 }
1007 }
1008
1009 if (!$matches) {
1010 $type = [new LegacyType(LegacyType::BUILTIN_TYPE_OBJECT, $parameter->allowsNull(), $parameterTypeName)];
1011 }
1012 }
1013 }
1014
1015 $parameterData = $this->validateAndDenormalizeLegacy($type, $class->getName(), $parameterName, $parameterData, $format, $context);
1016 $parameterData = $this->applyCallbacks($parameterData, $class->getName(), $parameterName, $format, $context);
1017
1018 return $this->applyFilterBool($parameter, $parameterData, $context);
1019 }
1020
1021 $parameterType = $parameter->getType();
1022 static $parameterTypeResolver;
1023 static $parameterTypeContextFactory;
1024
1025 if (null !== $parameterType && $parameterTypeResolver ??= class_exists(ReflectionTypeResolver::class) ? new ReflectionTypeResolver() : false) {
1026 $resolvedParameterType = $parameterTypeResolver->resolve($parameterType, ($parameterTypeContextFactory ??= new TypeContextFactory())->createFromClassName($class->name, $parameter->getDeclaringClass()?->name));
1027 if ($resolvedParameterType->isSatisfiedBy(static fn (Type $t) => match (true) {
1028 $t instanceof BuiltinType && !\in_array($t->getTypeIdentifier(), [TypeIdentifier::NULL, TypeIdentifier::MIXED], true) => !$type->isIdentifiedBy($t->getTypeIdentifier()),
1029 $t instanceof ObjectType => !$type->isIdentifiedBy($t->getClassName()),
1030 default => false,
1031 })) {
1032 $type = $resolvedParameterType;
1033 }
1034 } elseif ($parameterType instanceof \ReflectionNamedType) {
1035 if ($parameterType->isBuiltin()) {
1036 $typeIdentifier = TypeIdentifier::tryFrom($parameterType->getName());
1037
1038 if (null !== $typeIdentifier && TypeIdentifier::MIXED !== $typeIdentifier && !$type->isIdentifiedBy($typeIdentifier)) {
1039 $type = Type::builtin($typeIdentifier);
1040 }
1041 } elseif (!$type->isIdentifiedBy($parameterType->getName())) {
1042 $type = Type::object($parameterType->getName());
1043 }
1044 if ($parameter->allowsNull()) {
1045 $type = Type::nullable($type);
1046 }
1047 }
1048
1049 $parameterData = $this->validateAndDenormalize($type, $class->getName(), $parameterName, $parameterData, $format, $context);
1050 $parameterData = $this->applyCallbacks($parameterData, $class->getName(), $parameterName, $format, $context);
1051
1052 return $this->applyFilterBool($parameter, $parameterData, $context);
1053 }
1054
1055 /**
1056 * @return Type|list<LegacyType>|null
1057 */
1058 private function getType(string $currentClass, string $attribute): Type|array|null
1059 {
1060 if (null === $this->propertyTypeExtractor) {
1061 return null;
1062 }
1063
1064 $key = $currentClass.'::'.$attribute;
1065 if (isset($this->typeCache[$key])) {
1066 return false === $this->typeCache[$key] ? null : $this->typeCache[$key];
1067 }
1068
1069 if (null !== $type = $this->getPropertyType($currentClass, $attribute)) {
1070 return $this->typeCache[$key] = $type;
1071 }
1072
1073 if ($discriminatorMapping = $this->classDiscriminatorResolver?->getMappingForClass($currentClass)) {
1074 if ($discriminatorMapping->getTypeProperty() === $attribute) {
1075 return $this->typeCache[$key] = Type::string();
1076 }
1077
1078 foreach ($discriminatorMapping->getTypesMapping() as $mappedClass) {
1079 if (null !== $type = $this->getPropertyType($mappedClass, $attribute)) {
1080 return $this->typeCache[$key] = $type;
1081 }
1082 }
1083 }
1084
1085 $this->typeCache[$key] = false;
1086
1087 return null;
1088 }
1089
1090 /**
1091 * BC layer for PropertyTypeExtractorInterface::getTypes().
1092 * Can be removed as soon as PropertyTypeExtractorInterface::getTypes() is removed (8.0).
1093 *
1094 * @return Type|list<LegacyType>|null
1095 */
1096 private function getPropertyType(string $className, string $property): Type|array|null
1097 {
1098 if (class_exists(Type::class) && method_exists($this->propertyTypeExtractor, 'getType')) {
1099 return $this->propertyTypeExtractor->getType($className, $property);
1100 }
1101
1102 return $this->propertyTypeExtractor->getTypes($className, $property);
1103 }
1104
1105 /**
1106 * Sets an attribute and apply the name converter if necessary.
1107 */
1108 private function updateData(array $data, string $attribute, mixed $attributeValue, string $class, ?string $format, array $context, ?array $attributesMetadata, ?ClassMetadataInterface $classMetadata): array
1109 {
1110 if (null === $attributeValue && ($context[self::SKIP_NULL_VALUES] ?? $this->defaultContext[self::SKIP_NULL_VALUES] ?? false)) {
1111 return $data;
1112 }
1113
1114 if (null !== $classMetadata && null !== $serializedPath = ($attributesMetadata[$attribute] ?? null)?->getSerializedPath()) {
1115 $propertyAccessor = PropertyAccess::createPropertyAccessor();
1116 if ($propertyAccessor->isReadable($data, $serializedPath) && null !== $propertyAccessor->getValue($data, $serializedPath)) {
1117 throw new LogicException(\sprintf('The element you are trying to set is already populated: "%s".', (string) $serializedPath));
1118 }
1119 $propertyAccessor->setValue($data, $serializedPath, $attributeValue);
1120
1121 return $data;
1122 }
1123
1124 if ($this->nameConverter) {
1125 $attribute = $this->nameConverter->normalize($attribute, $class, $format, $context);
1126 }
1127
1128 $data[$attribute] = $attributeValue;
1129
1130 return $data;
1131 }
1132
1133 /**
1134 * Is the max depth reached for the given attribute?
1135 *
1136 * @param AttributeMetadataInterface[] $attributesMetadata
1137 */
1138 private function isMaxDepthReached(array $attributesMetadata, string $class, string $attribute, array &$context): bool
1139 {
1140 if (!($context[self::ENABLE_MAX_DEPTH] ?? $this->defaultContext[self::ENABLE_MAX_DEPTH] ?? false)
1141 || !isset($attributesMetadata[$attribute]) || null === $maxDepth = $attributesMetadata[$attribute]?->getMaxDepth()
1142 ) {
1143 return false;
1144 }
1145
1146 $key = \sprintf(self::DEPTH_KEY_PATTERN, $class, $attribute);
1147 if (!isset($context[$key])) {
1148 $context[$key] = 1;
1149
1150 return false;
1151 }
1152
1153 if ($context[$key] === $maxDepth) {
1154 return true;
1155 }
1156
1157 ++$context[$key];
1158
1159 return false;
1160 }
1161
1162 /**
1163 * Overwritten to update the cache key for the child.
1164 *
1165 * We must not mix up the attribute cache between parent and children.
1166 *
1167 * @internal
1168 */
1169 protected function createChildContext(array $parentContext, string $attribute, ?string $format): array
1170 {
1171 $context = parent::createChildContext($parentContext, $attribute, $format);
1172 if ($context['cache_key'] ?? false) {
1173 $context['cache_key'] .= '-'.$attribute;
1174 } elseif (false !== ($context['cache_key'] ?? null)) {
1175 $context['cache_key'] = $this->getCacheKey($format, $context);
1176 }
1177
1178 return $context;
1179 }
1180
1181 protected function getAllowedAttributes(string|object $classOrObject, array $context, bool $attributesAsString = false): array|bool
1182 {
1183 if (false === $allowedAttributes = parent::getAllowedAttributes($classOrObject, $context, $attributesAsString)) {
1184 return false;
1185 }
1186
1187 if (null !== $this->classDiscriminatorResolver) {
1188 $class = \is_object($classOrObject) ? $classOrObject::class : $classOrObject;
1189 if (null !== $discriminatorMapping = $this->classDiscriminatorResolver->getMappingForMappedObject($classOrObject)) {
1190 $allowedAttributes[] = $attributesAsString ? $discriminatorMapping->getTypeProperty() : new AttributeMetadata($discriminatorMapping->getTypeProperty());
1191 }
1192
1193 if (null !== $discriminatorMapping = $this->classDiscriminatorResolver->getMappingForClass($class)) {
1194 $attributes = [];
1195 foreach ($discriminatorMapping->getTypesMapping() as $mappedClass) {
1196 $attributes[] = parent::getAllowedAttributes($mappedClass, $context, $attributesAsString);
1197 }
1198 $allowedAttributes = array_merge($allowedAttributes, ...$attributes);
1199 }
1200 }
1201
1202 return $allowedAttributes;
1203 }
1204
1205 /**
1206 * Builds the cache key for the attributes cache.
1207 *
1208 * The key must be different for every option in the context that could change which attributes should be handled.
1209 */
1210 private function getCacheKey(?string $format, array $context): bool|string
1211 {
1212 foreach ($context[self::EXCLUDE_FROM_CACHE_KEY] ?? $this->defaultContext[self::EXCLUDE_FROM_CACHE_KEY] as $key) {
1213 unset($context[$key]);
1214 }
1215 unset($context[self::EXCLUDE_FROM_CACHE_KEY]);
1216 unset($context[self::OBJECT_TO_POPULATE]);
1217 unset($context['cache_key']); // avoid artificially different keys
1218
1219 try {
1220 return hash('xxh128', $format.serialize([
1221 'context' => $context,
1222 'ignored' => $context[self::IGNORED_ATTRIBUTES] ?? $this->defaultContext[self::IGNORED_ATTRIBUTES],
1223 ]));
1224 } catch (\Exception) {
1225 // The context cannot be serialized, skip the cache
1226 return false;
1227 }
1228 }
1229
1230 /**
1231 * Returns all attributes with a SerializedPath attribute and the respective path.
1232 */
1233 private function getNestedAttributes(string $class): array
1234 {
1235 if (!$this->classMetadataFactory?->hasMetadataFor($class)) {
1236 return [];
1237 }
1238
1239 $properties = [];
1240 $serializedPaths = [];
1241 $classMetadata = $this->classMetadataFactory->getMetadataFor($class);
1242 foreach ($classMetadata->getAttributesMetadata() as $name => $metadata) {
1243 if (!$serializedPath = $metadata->getSerializedPath()) {
1244 continue;
1245 }
1246 $pathIdentifier = implode(',', $serializedPath->getElements());
1247 if (isset($serializedPaths[$pathIdentifier])) {
1248 throw new LogicException(\sprintf('Duplicate serialized path: "%s" used for properties "%s" and "%s".', $pathIdentifier, $serializedPaths[$pathIdentifier], $name));
1249 }
1250 $serializedPaths[$pathIdentifier] = $name;
1251 $properties[$name] = $serializedPath;
1252 }
1253
1254 return $properties;
1255 }
1256
1257 private function removeNestedValue(array $path, array $data): array
1258 {
1259 $element = array_shift($path);
1260 if (!$path || !$data[$element] || !$data[$element] = $this->removeNestedValue($path, $data[$element])) {
1261 unset($data[$element]);
1262 }
1263
1264 return $data;
1265 }
1266
1267 /**
1268 * @return class-string
1269 */
1270 private function getMappedClass(array $data, string $class, array $context): string
1271 {
1272 if (null !== $object = $this->extractObjectToPopulate($class, $context, self::OBJECT_TO_POPULATE)) {
1273 return $object::class;
1274 }
1275
1276 if (!$mapping = $this->classDiscriminatorResolver?->getMappingForClass($class)) {
1277 return $class;
1278 }
1279
1280 if (null === $type = $data[$mapping->getTypeProperty()] ?? $mapping->getDefaultType()) {
1281 throw NotNormalizableValueException::createForUnexpectedDataType(\sprintf('Type property "%s" not found for the abstract object "%s".', $mapping->getTypeProperty(), $class), null, ['string'], isset($context['deserialization_path']) ? $context['deserialization_path'].'.'.$mapping->getTypeProperty() : $mapping->getTypeProperty(), false);
1282 }
1283
1284 if (!\is_string($type) && (!\is_object($type) || !method_exists($type, '__toString'))) {
1285 throw NotNormalizableValueException::createForUnexpectedDataType(\sprintf('The type property "%s" for the abstract object "%s" must be a string or a stringable object.', $mapping->getTypeProperty(), $class), $type, ['string'], isset($context['deserialization_path']) ? $context['deserialization_path'].'.'.$mapping->getTypeProperty() : $mapping->getTypeProperty(), false);
1286 }
1287
1288 if (null === $mappedClass = $mapping->getClassForType($type)) {
1289 throw NotNormalizableValueException::createForUnexpectedDataType(\sprintf('The type "%s" is not a valid value.', $type), $type, ['string'], isset($context['deserialization_path']) ? $context['deserialization_path'].'.'.$mapping->getTypeProperty() : $mapping->getTypeProperty(), true);
1290 }
1291
1292 return $mappedClass;
1293 }
1294 }