• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

api-platform / core / 15187574500

22 May 2025 01:14PM UTC coverage: 27.347%. Remained the same
15187574500

push

github

soyuka
docs: changelog 4.1.11

13482 of 49299 relevant lines covered (27.35%)

74.57 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

86.71
/src/Serializer/AbstractItemNormalizer.php
1
<?php
2

3
/*
4
 * This file is part of the API Platform project.
5
 *
6
 * (c) Kévin Dunglas <dunglas@gmail.com>
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
declare(strict_types=1);
13

14
namespace ApiPlatform\Serializer;
15

16
use ApiPlatform\Metadata\ApiProperty;
17
use ApiPlatform\Metadata\CollectionOperationInterface;
18
use ApiPlatform\Metadata\Exception\InvalidArgumentException;
19
use ApiPlatform\Metadata\Exception\ItemNotFoundException;
20
use ApiPlatform\Metadata\IriConverterInterface;
21
use ApiPlatform\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
22
use ApiPlatform\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
23
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
24
use ApiPlatform\Metadata\ResourceAccessCheckerInterface;
25
use ApiPlatform\Metadata\ResourceClassResolverInterface;
26
use ApiPlatform\Metadata\UrlGeneratorInterface;
27
use ApiPlatform\Metadata\Util\ClassInfoTrait;
28
use ApiPlatform\Metadata\Util\CloneTrait;
29
use Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException;
30
use Symfony\Component\PropertyAccess\PropertyAccess;
31
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
32
use Symfony\Component\PropertyInfo\Type;
33
use Symfony\Component\Serializer\Encoder\CsvEncoder;
34
use Symfony\Component\Serializer\Encoder\XmlEncoder;
35
use Symfony\Component\Serializer\Exception\LogicException;
36
use Symfony\Component\Serializer\Exception\MissingConstructorArgumentsException;
37
use Symfony\Component\Serializer\Exception\NotNormalizableValueException;
38
use Symfony\Component\Serializer\Exception\RuntimeException;
39
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
40
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
41
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
42
use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer;
43
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
44
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
45

46
/**
47
 * Base item normalizer.
48
 *
49
 * @author Kévin Dunglas <dunglas@gmail.com>
50
 */
51
abstract class AbstractItemNormalizer extends AbstractObjectNormalizer
52
{
53
    use ClassInfoTrait;
54
    use CloneTrait;
55
    use ContextTrait;
56
    use InputOutputMetadataTrait;
57
    use OperationContextTrait;
58

59
    protected PropertyAccessorInterface $propertyAccessor;
60
    protected array $localCache = [];
61
    protected array $localFactoryOptionsCache = [];
62
    protected ?ResourceAccessCheckerInterface $resourceAccessChecker;
63

64
    public function __construct(protected PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, protected PropertyMetadataFactoryInterface $propertyMetadataFactory, protected IriConverterInterface $iriConverter, protected ResourceClassResolverInterface $resourceClassResolver, ?PropertyAccessorInterface $propertyAccessor = null, ?NameConverterInterface $nameConverter = null, ?ClassMetadataFactoryInterface $classMetadataFactory = null, array $defaultContext = [], ?ResourceMetadataCollectionFactoryInterface $resourceMetadataCollectionFactory = null, ?ResourceAccessCheckerInterface $resourceAccessChecker = null, protected ?TagCollectorInterface $tagCollector = null)
65
    {
66
        if (!isset($defaultContext['circular_reference_handler'])) {
2,064✔
67
            $defaultContext['circular_reference_handler'] = fn ($object): ?string => $this->iriConverter->getIriFromResource($object);
2,052✔
68
        }
69

70
        parent::__construct($classMetadataFactory, $nameConverter, null, null, \Closure::fromCallable($this->getObjectClass(...)), $defaultContext);
2,064✔
71
        $this->propertyAccessor = $propertyAccessor ?: PropertyAccess::createPropertyAccessor();
2,064✔
72
        $this->resourceAccessChecker = $resourceAccessChecker;
2,064✔
73
        $this->resourceMetadataCollectionFactory = $resourceMetadataCollectionFactory;
2,064✔
74
    }
75

76
    /**
77
     * {@inheritdoc}
78
     */
79
    public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
80
    {
81
        if (!\is_object($data) || is_iterable($data)) {
1,813✔
82
            return false;
682✔
83
        }
84

85
        $class = $context['force_resource_class'] ?? $this->getObjectClass($data);
1,753✔
86
        if (($context['output']['class'] ?? null) === $class) {
1,753✔
87
            return true;
43✔
88
        }
89

90
        return $this->resourceClassResolver->isResourceClass($class);
1,737✔
91
    }
92

93
    public function getSupportedTypes(?string $format): array
94
    {
95
        return [
1,872✔
96
            'object' => true,
1,872✔
97
        ];
1,872✔
98
    }
99

100
    /**
101
     * {@inheritdoc}
102
     *
103
     * @throws LogicException
104
     */
105
    public function normalize(mixed $object, ?string $format = null, array $context = []): array|string|int|float|bool|\ArrayObject|null
106
    {
107
        $resourceClass = $context['force_resource_class'] ?? $this->getObjectClass($object);
1,759✔
108
        if ($outputClass = $this->getOutputClass($context)) {
1,759✔
109
            if (!$this->serializer instanceof NormalizerInterface) {
43✔
110
                throw new LogicException('Cannot normalize the output because the injected serializer is not a normalizer');
×
111
            }
112

113
            unset($context['output'], $context['operation'], $context['operation_name']);
43✔
114
            $context['resource_class'] = $outputClass;
43✔
115
            $context['api_sub_level'] = true;
43✔
116
            $context[self::ALLOW_EXTRA_ATTRIBUTES] = false;
43✔
117

118
            return $this->serializer->normalize($object, $format, $context);
43✔
119
        }
120

121
        // Never remove this, with `application/json` we don't use our AbstractCollectionNormalizer and we need
122
        // to remove the collection operation from our context or we'll introduce security issues
123
        if (isset($context['operation']) && $context['operation'] instanceof CollectionOperationInterface) {
1,759✔
124
            unset($context['operation_name'], $context['operation'], $context['iri']);
16✔
125
        }
126

127
        if ($this->resourceClassResolver->isResourceClass($resourceClass)) {
1,759✔
128
            $context = $this->initContext($resourceClass, $context);
1,719✔
129
        }
130

131
        $context['api_normalize'] = true;
1,759✔
132
        $iri = $context['iri'] ??= $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_URL, $context['operation'] ?? null, $context);
1,759✔
133

134
        /*
135
         * When true, converts the normalized data array of a resource into an
136
         * IRI, if the normalized data array is empty.
137
         *
138
         * This is useful when traversing from a non-resource towards an attribute
139
         * which is a resource, as we do not have the benefit of {@see ApiProperty::isReadableLink}.
140
         *
141
         * It must not be propagated to resources, as {@see ApiProperty::isReadableLink}
142
         * should take effect.
143
         */
144
        $emptyResourceAsIri = $context['api_empty_resource_as_iri'] ?? false;
1,759✔
145
        unset($context['api_empty_resource_as_iri']);
1,759✔
146

147
        if (!$this->tagCollector && isset($context['resources'])) {
1,759✔
148
            $context['resources'][$iri] = $iri;
×
149
        }
150

151
        $context['object'] = $object;
1,759✔
152
        $context['format'] = $format;
1,759✔
153

154
        $data = parent::normalize($object, $format, $context);
1,759✔
155

156
        $context['data'] = $data;
1,759✔
157
        unset($context['property_metadata'], $context['api_attribute']);
1,759✔
158

159
        if ($emptyResourceAsIri && \is_array($data) && 0 === \count($data)) {
1,759✔
160
            $context['data'] = $iri;
×
161

162
            if ($this->tagCollector) {
×
163
                $this->tagCollector->collect($context);
×
164
            }
165

166
            return $iri;
×
167
        }
168

169
        if ($this->tagCollector) {
1,759✔
170
            $this->tagCollector->collect($context);
1,540✔
171
        }
172

173
        return $data;
1,759✔
174
    }
175

176
    /**
177
     * {@inheritdoc}
178
     */
179
    public function supportsDenormalization(mixed $data, string $type, ?string $format = null, array $context = []): bool
180
    {
181
        if (($context['input']['class'] ?? null) === $type) {
491✔
182
            return true;
×
183
        }
184

185
        return $this->localCache[$type] ?? $this->localCache[$type] = $this->resourceClassResolver->isResourceClass($type);
491✔
186
    }
187

188
    /**
189
     * {@inheritdoc}
190
     */
191
    public function denormalize(mixed $data, string $class, ?string $format = null, array $context = []): mixed
192
    {
193
        $resourceClass = $class;
485✔
194

195
        if ($inputClass = $this->getInputClass($context)) {
485✔
196
            if (!$this->serializer instanceof DenormalizerInterface) {
25✔
197
                throw new LogicException('Cannot denormalize the input because the injected serializer is not a denormalizer');
×
198
            }
199

200
            unset($context['input'], $context['operation'], $context['operation_name'], $context['uri_variables']);
25✔
201
            $context['resource_class'] = $inputClass;
25✔
202

203
            try {
204
                return $this->serializer->denormalize($data, $inputClass, $format, $context);
25✔
205
            } catch (NotNormalizableValueException $e) {
2✔
206
                throw new UnexpectedValueException('The input data is misformatted.', $e->getCode(), $e);
2✔
207
            }
208
        }
209

210
        if (null === $objectToPopulate = $this->extractObjectToPopulate($resourceClass, $context, static::OBJECT_TO_POPULATE)) {
465✔
211
            $normalizedData = \is_scalar($data) ? [$data] : $this->prepareForDenormalization($data);
382✔
212
            $class = $this->getClassDiscriminatorResolvedClass($normalizedData, $class, $context);
382✔
213
        }
214

215
        $context['api_denormalize'] = true;
465✔
216

217
        if ($this->resourceClassResolver->isResourceClass($class)) {
465✔
218
            $resourceClass = $this->resourceClassResolver->getResourceClass($objectToPopulate, $class);
465✔
219
            $context['resource_class'] = $resourceClass;
465✔
220
        }
221

222
        if (\is_string($data)) {
465✔
223
            try {
224
                return $this->iriConverter->getResourceFromIri($data, $context + ['fetch_data' => true]);
5✔
225
            } catch (ItemNotFoundException $e) {
×
226
                if (!isset($context['not_normalizable_value_exceptions'])) {
×
227
                    throw new UnexpectedValueException($e->getMessage(), $e->getCode(), $e);
×
228
                }
229

230
                throw NotNormalizableValueException::createForUnexpectedDataType($e->getMessage(), $data, [$resourceClass], $context['deserialization_path'] ?? null, true, $e->getCode(), $e);
×
231
            } catch (InvalidArgumentException $e) {
×
232
                if (!isset($context['not_normalizable_value_exceptions'])) {
×
233
                    throw new UnexpectedValueException(\sprintf('Invalid IRI "%s".', $data), $e->getCode(), $e);
×
234
                }
235

236
                throw NotNormalizableValueException::createForUnexpectedDataType(\sprintf('Invalid IRI "%s".', $data), $data, [$resourceClass], $context['deserialization_path'] ?? null, true, $e->getCode(), $e);
×
237
            }
238
        }
239

240
        if (!\is_array($data)) {
461✔
241
            throw NotNormalizableValueException::createForUnexpectedDataType(\sprintf('The type of the "%s" resource must be "array" (nested document) or "string" (IRI), "%s" given.', $resourceClass, \gettype($data)), $data, [Type::BUILTIN_TYPE_ARRAY, Type::BUILTIN_TYPE_STRING], $context['deserialization_path'] ?? null);
2✔
242
        }
243

244
        $previousObject = $this->clone($objectToPopulate);
461✔
245
        $object = parent::denormalize($data, $class, $format, $context);
461✔
246

247
        if (!$this->resourceClassResolver->isResourceClass($class)) {
429✔
248
            return $object;
×
249
        }
250

251
        // Bypass the post-denormalize attribute revert logic if the object could not be
252
        // cloned since we cannot possibly revert any changes made to it.
253
        if (null !== $objectToPopulate && null === $previousObject) {
429✔
254
            return $object;
×
255
        }
256

257
        $options = $this->getFactoryOptions($context);
429✔
258
        $propertyNames = iterator_to_array($this->propertyNameCollectionFactory->create($resourceClass, $options));
429✔
259

260
        // Revert attributes that aren't allowed to be changed after a post-denormalize check
261
        foreach (array_keys($data) as $attribute) {
429✔
262
            $attribute = $this->nameConverter ? $this->nameConverter->denormalize((string) $attribute) : $attribute;
411✔
263
            if (!\in_array($attribute, $propertyNames, true)) {
411✔
264
                continue;
90✔
265
            }
266

267
            if (!$this->canAccessAttributePostDenormalize($object, $previousObject, $attribute, $context)) {
390✔
268
                if (null !== $previousObject) {
4✔
269
                    $this->setValue($object, $attribute, $this->propertyAccessor->getValue($previousObject, $attribute));
1✔
270
                } else {
271
                    $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $attribute, $options);
3✔
272
                    $this->setValue($object, $attribute, $propertyMetadata->getDefault());
3✔
273
                }
274
            }
275
        }
276

277
        return $object;
429✔
278
    }
279

280
    /**
281
     * Method copy-pasted from symfony/serializer.
282
     * Remove it after symfony/serializer version update @see https://github.com/symfony/symfony/pull/28263.
283
     *
284
     * {@inheritdoc}
285
     *
286
     * @internal
287
     */
288
    protected function instantiateObject(array &$data, string $class, array &$context, \ReflectionClass $reflectionClass, array|bool $allowedAttributes, ?string $format = null): object
289
    {
290
        if (null !== $object = $this->extractObjectToPopulate($class, $context, static::OBJECT_TO_POPULATE)) {
461✔
291
            unset($context[static::OBJECT_TO_POPULATE]);
97✔
292

293
            return $object;
97✔
294
        }
295

296
        $class = $this->getClassDiscriminatorResolvedClass($data, $class, $context);
378✔
297
        $reflectionClass = new \ReflectionClass($class);
378✔
298

299
        $constructor = $this->getConstructor($data, $class, $context, $reflectionClass, $allowedAttributes);
378✔
300
        if ($constructor) {
378✔
301
            $constructorParameters = $constructor->getParameters();
175✔
302

303
            $params = [];
175✔
304
            $missingConstructorArguments = [];
175✔
305
            foreach ($constructorParameters as $constructorParameter) {
175✔
306
                $paramName = $constructorParameter->name;
77✔
307
                $key = $this->nameConverter ? $this->nameConverter->normalize($paramName, $class, $format, $context) : $paramName;
77✔
308
                $attributeContext = $this->getAttributeDenormalizationContext($class, $paramName, $context);
77✔
309
                $attributeContext['deserialization_path'] = $attributeContext['deserialization_path'] ?? $key;
77✔
310

311
                $allowed = false === $allowedAttributes || (\is_array($allowedAttributes) && \in_array($paramName, $allowedAttributes, true));
77✔
312
                $ignored = !$this->isAllowedAttribute($class, $paramName, $format, $context);
77✔
313
                if ($constructorParameter->isVariadic()) {
77✔
314
                    if ($allowed && !$ignored && (isset($data[$key]) || \array_key_exists($key, $data))) {
×
315
                        if (!\is_array($data[$paramName])) {
×
316
                            throw new RuntimeException(\sprintf('Cannot create an instance of %s from serialized data because the variadic parameter %s can only accept an array.', $class, $constructorParameter->name));
×
317
                        }
318

319
                        $params[] = $data[$paramName];
×
320
                    }
321
                } elseif ($allowed && !$ignored && (isset($data[$key]) || \array_key_exists($key, $data))) {
77✔
322
                    try {
323
                        $params[] = $this->createConstructorArgument($data[$key], $key, $constructorParameter, $attributeContext, $format);
23✔
324
                    } catch (NotNormalizableValueException $exception) {
4✔
325
                        if (!isset($context['not_normalizable_value_exceptions'])) {
4✔
326
                            throw $exception;
3✔
327
                        }
328
                        $context['not_normalizable_value_exceptions'][] = $exception;
1✔
329
                    }
330

331
                    // Don't run set for a parameter passed to the constructor
332
                    unset($data[$key]);
20✔
333
                } elseif (isset($context[static::DEFAULT_CONSTRUCTOR_ARGUMENTS][$class][$key])) {
68✔
334
                    $params[] = $context[static::DEFAULT_CONSTRUCTOR_ARGUMENTS][$class][$key];
×
335
                } elseif ($constructorParameter->isDefaultValueAvailable()) {
68✔
336
                    $params[] = $constructorParameter->getDefaultValue();
67✔
337
                } else {
338
                    if (!isset($context['not_normalizable_value_exceptions'])) {
3✔
339
                        $missingConstructorArguments[] = $constructorParameter->name;
2✔
340
                    }
341

342
                    $constructorParameterType = 'unknown';
3✔
343
                    $reflectionType = $constructorParameter->getType();
3✔
344
                    if ($reflectionType instanceof \ReflectionNamedType) {
3✔
345
                        $constructorParameterType = $reflectionType->getName();
3✔
346
                    }
347

348
                    $exception = NotNormalizableValueException::createForUnexpectedDataType(
3✔
349
                        \sprintf('Failed to create object because the class misses the "%s" property.', $constructorParameter->name),
3✔
350
                        null,
3✔
351
                        [$constructorParameterType],
3✔
352
                        $attributeContext['deserialization_path'],
3✔
353
                        true
3✔
354
                    );
3✔
355
                    $context['not_normalizable_value_exceptions'][] = $exception;
3✔
356
                }
357
            }
358

359
            if ($missingConstructorArguments) {
172✔
360
                throw new MissingConstructorArgumentsException(\sprintf('Cannot create an instance of "%s" from serialized data because its constructor requires the following parameters to be present : "$%s".', $class, implode('", "$', $missingConstructorArguments)), 0, null, $missingConstructorArguments, $class);
2✔
361
            }
362

363
            if (\count($context['not_normalizable_value_exceptions'] ?? []) > 0) {
172✔
364
                return $reflectionClass->newInstanceWithoutConstructor();
1✔
365
            }
366

367
            if ($constructor->isConstructor()) {
171✔
368
                return $reflectionClass->newInstanceArgs($params);
171✔
369
            }
370

371
            return $constructor->invokeArgs(null, $params);
×
372
        }
373

374
        return new $class();
214✔
375
    }
376

377
    protected function getClassDiscriminatorResolvedClass(array $data, string $class, array $context = []): string
378
    {
379
        if (null === $this->classDiscriminatorResolver || (null === $mapping = $this->classDiscriminatorResolver->getMappingForClass($class))) {
382✔
380
            return $class;
382✔
381
        }
382

383
        if (!isset($data[$mapping->getTypeProperty()])) {
2✔
384
            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());
×
385
        }
386

387
        $type = $data[$mapping->getTypeProperty()];
2✔
388
        if (null === ($mappedClass = $mapping->getClassForType($type))) {
2✔
389
            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);
×
390
        }
391

392
        return $mappedClass;
2✔
393
    }
394

395
    protected function createConstructorArgument($parameterData, string $key, \ReflectionParameter $constructorParameter, array $context, ?string $format = null): mixed
396
    {
397
        return $this->createAndValidateAttributeValue($constructorParameter->name, $parameterData, $format, $context);
23✔
398
    }
399

400
    /**
401
     * {@inheritdoc}
402
     *
403
     * Unused in this context.
404
     *
405
     * @return string[]
406
     */
407
    protected function extractAttributes($object, $format = null, array $context = []): array
408
    {
409
        return [];
×
410
    }
411

412
    /**
413
     * {@inheritdoc}
414
     */
415
    protected function getAllowedAttributes(string|object $classOrObject, array $context, bool $attributesAsString = false): array|bool
416
    {
417
        if (!$this->resourceClassResolver->isResourceClass($context['resource_class'])) {
1,773✔
418
            return parent::getAllowedAttributes($classOrObject, $context, $attributesAsString);
43✔
419
        }
420

421
        $resourceClass = $this->resourceClassResolver->getResourceClass(null, $context['resource_class']); // fix for abstract classes and interfaces
1,735✔
422
        $options = $this->getFactoryOptions($context);
1,735✔
423
        $propertyNames = $this->propertyNameCollectionFactory->create($resourceClass, $options);
1,735✔
424

425
        $allowedAttributes = [];
1,735✔
426
        foreach ($propertyNames as $propertyName) {
1,735✔
427
            $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $propertyName, $options);
1,721✔
428

429
            if (
430
                $this->isAllowedAttribute($classOrObject, $propertyName, null, $context)
1,721✔
431
                && (isset($context['api_normalize']) && $propertyMetadata->isReadable()
1,721✔
432
                    || isset($context['api_denormalize']) && ($propertyMetadata->isWritable() || !\is_object($classOrObject) && $propertyMetadata->isInitializable())
1,721✔
433
                )
434
            ) {
435
                $allowedAttributes[] = $propertyName;
1,707✔
436
            }
437
        }
438

439
        return $allowedAttributes;
1,735✔
440
    }
441

442
    /**
443
     * {@inheritdoc}
444
     */
445
    protected function isAllowedAttribute(object|string $classOrObject, string $attribute, ?string $format = null, array $context = []): bool
446
    {
447
        if (!parent::isAllowedAttribute($classOrObject, $attribute, $format, $context)) {
1,759✔
448
            return false;
440✔
449
        }
450

451
        return $this->canAccessAttribute(\is_object($classOrObject) ? $classOrObject : null, $attribute, $context);
1,757✔
452
    }
453

454
    /**
455
     * Check if access to the attribute is granted.
456
     */
457
    protected function canAccessAttribute(?object $object, string $attribute, array $context = []): bool
458
    {
459
        if (!$this->resourceClassResolver->isResourceClass($context['resource_class'])) {
1,757✔
460
            return true;
43✔
461
        }
462

463
        $options = $this->getFactoryOptions($context);
1,719✔
464
        $propertyMetadata = $this->propertyMetadataFactory->create($context['resource_class'], $attribute, $options);
1,719✔
465
        $security = $propertyMetadata->getSecurity() ?? $propertyMetadata->getPolicy();
1,719✔
466
        if (null !== $this->resourceAccessChecker && $security) {
1,719✔
467
            return $this->resourceAccessChecker->isGranted($context['resource_class'], $security, [
64✔
468
                'object' => $object,
64✔
469
                'property' => $attribute,
64✔
470
            ]);
64✔
471
        }
472

473
        return true;
1,711✔
474
    }
475

476
    /**
477
     * Check if access to the attribute is granted.
478
     */
479
    protected function canAccessAttributePostDenormalize(?object $object, ?object $previousObject, string $attribute, array $context = []): bool
480
    {
481
        $options = $this->getFactoryOptions($context);
390✔
482
        $propertyMetadata = $this->propertyMetadataFactory->create($context['resource_class'], $attribute, $options);
390✔
483
        $security = $propertyMetadata->getSecurityPostDenormalize();
390✔
484
        if ($this->resourceAccessChecker && $security) {
390✔
485
            return $this->resourceAccessChecker->isGranted($context['resource_class'], $security, [
10✔
486
                'object' => $object,
10✔
487
                'previous_object' => $previousObject,
10✔
488
                'property' => $attribute,
10✔
489
            ]);
10✔
490
        }
491

492
        return true;
388✔
493
    }
494

495
    /**
496
     * {@inheritdoc}
497
     */
498
    protected function setAttributeValue(object $object, string $attribute, mixed $value, ?string $format = null, array $context = []): void
499
    {
500
        try {
501
            $this->setValue($object, $attribute, $this->createAttributeValue($attribute, $value, $format, $context));
393✔
502
        } catch (NotNormalizableValueException $exception) {
30✔
503
            // Only throw if collecting denormalization errors is disabled.
504
            if (!isset($context['not_normalizable_value_exceptions'])) {
20✔
505
                throw $exception;
19✔
506
            }
507
        }
508
    }
509

510
    /**
511
     * Validates the type of the value. Allows using integers as floats for JSON formats.
512
     *
513
     * @throws NotNormalizableValueException
514
     */
515
    protected function validateType(string $attribute, Type $type, mixed $value, ?string $format = null, array $context = []): void
516
    {
517
        $builtinType = $type->getBuiltinType();
338✔
518
        if (Type::BUILTIN_TYPE_FLOAT === $builtinType && null !== $format && str_contains($format, 'json')) {
338✔
519
            $isValid = \is_float($value) || \is_int($value);
2✔
520
        } else {
521
            $isValid = \call_user_func('is_'.$builtinType, $value);
338✔
522
        }
523

524
        if (!$isValid) {
338✔
525
            throw NotNormalizableValueException::createForUnexpectedDataType(\sprintf('The type of the "%s" attribute must be "%s", "%s" given.', $attribute, $builtinType, \gettype($value)), $value, [$builtinType], $context['deserialization_path'] ?? null);
14✔
526
        }
527
    }
528

529
    /**
530
     * Denormalizes a collection of objects.
531
     *
532
     * @throws NotNormalizableValueException
533
     */
534
    protected function denormalizeCollection(string $attribute, ApiProperty $propertyMetadata, Type $type, string $className, mixed $value, ?string $format, array $context): array
535
    {
536
        if (!\is_array($value)) {
31✔
537
            throw NotNormalizableValueException::createForUnexpectedDataType(\sprintf('The type of the "%s" attribute must be "array", "%s" given.', $attribute, \gettype($value)), $value, [Type::BUILTIN_TYPE_ARRAY], $context['deserialization_path'] ?? null);
3✔
538
        }
539

540
        $values = [];
28✔
541
        $childContext = $this->createChildContext($this->createOperationContext($context, $className), $attribute, $format);
28✔
542
        $collectionKeyTypes = $type->getCollectionKeyTypes();
28✔
543
        foreach ($value as $index => $obj) {
28✔
544
            $currentChildContext = $childContext;
28✔
545
            if (isset($childContext['deserialization_path'])) {
28✔
546
                $currentChildContext['deserialization_path'] = "{$childContext['deserialization_path']}[{$index}]";
28✔
547
            }
548

549
            // no typehint provided on collection key
550
            if (!$collectionKeyTypes) {
28✔
551
                $values[$index] = $this->denormalizeRelation($attribute, $propertyMetadata, $className, $obj, $format, $currentChildContext);
×
552
                continue;
×
553
            }
554

555
            // validate collection key typehint
556
            foreach ($collectionKeyTypes as $collectionKeyType) {
28✔
557
                $collectionKeyBuiltinType = $collectionKeyType->getBuiltinType();
28✔
558
                if (!\call_user_func('is_'.$collectionKeyBuiltinType, $index)) {
28✔
559
                    continue;
2✔
560
                }
561

562
                $values[$index] = $this->denormalizeRelation($attribute, $propertyMetadata, $className, $obj, $format, $currentChildContext);
26✔
563
                continue 2;
26✔
564
            }
565
            throw NotNormalizableValueException::createForUnexpectedDataType(\sprintf('The type of the key "%s" must be "%s", "%s" given.', $index, $collectionKeyTypes[0]->getBuiltinType(), \gettype($index)), $index, [$collectionKeyTypes[0]->getBuiltinType()], ($context['deserialization_path'] ?? false) ? \sprintf('key(%s)', $context['deserialization_path']) : null, true);
2✔
566
        }
567

568
        return $values;
26✔
569
    }
570

571
    /**
572
     * Denormalizes a relation.
573
     *
574
     * @throws LogicException
575
     * @throws UnexpectedValueException
576
     * @throws NotNormalizableValueException
577
     */
578
    protected function denormalizeRelation(string $attributeName, ApiProperty $propertyMetadata, string $className, mixed $value, ?string $format, array $context): ?object
579
    {
580
        if (\is_string($value)) {
111✔
581
            try {
582
                return $this->iriConverter->getResourceFromIri($value, $context + ['fetch_data' => true]);
62✔
583
            } catch (ItemNotFoundException $e) {
8✔
584
                if (!isset($context['not_normalizable_value_exceptions'])) {
2✔
585
                    throw new UnexpectedValueException($e->getMessage(), $e->getCode(), $e);
2✔
586
                }
587

588
                throw NotNormalizableValueException::createForUnexpectedDataType($e->getMessage(), $value, [$className], $context['deserialization_path'] ?? null, true, $e->getCode(), $e);
×
589
            } catch (InvalidArgumentException $e) {
6✔
590
                if (!isset($context['not_normalizable_value_exceptions'])) {
4✔
591
                    throw new UnexpectedValueException(\sprintf('Invalid IRI "%s".', $value), $e->getCode(), $e);
4✔
592
                }
593

594
                throw NotNormalizableValueException::createForUnexpectedDataType(\sprintf('Invalid IRI "%s".', $value), $value, [$className], $context['deserialization_path'] ?? null, true, $e->getCode(), $e);
×
595
            }
596
        }
597

598
        if ($propertyMetadata->isWritableLink()) {
51✔
599
            $context['api_allow_update'] = true;
49✔
600

601
            if (!$this->serializer instanceof DenormalizerInterface) {
49✔
602
                throw new LogicException(\sprintf('The injected serializer must be an instance of "%s".', DenormalizerInterface::class));
×
603
            }
604

605
            $item = $this->serializer->denormalize($value, $className, $format, $context);
49✔
606
            if (!\is_object($item) && null !== $item) {
45✔
607
                throw new \UnexpectedValueException('Expected item to be an object or null.');
×
608
            }
609

610
            return $item;
45✔
611
        }
612

613
        if (!\is_array($value)) {
2✔
614
            throw NotNormalizableValueException::createForUnexpectedDataType(\sprintf('The type of the "%s" attribute must be "array" (nested document) or "string" (IRI), "%s" given.', $attributeName, \gettype($value)), $value, [Type::BUILTIN_TYPE_ARRAY, Type::BUILTIN_TYPE_STRING], $context['deserialization_path'] ?? null, true);
1✔
615
        }
616

617
        throw NotNormalizableValueException::createForUnexpectedDataType(\sprintf('Nested documents for attribute "%s" are not allowed. Use IRIs instead.', $attributeName), $value, [Type::BUILTIN_TYPE_ARRAY, Type::BUILTIN_TYPE_STRING], $context['deserialization_path'] ?? null, true);
1✔
618
    }
619

620
    /**
621
     * Gets the options for the property name collection / property metadata factories.
622
     */
623
    protected function getFactoryOptions(array $context): array
624
    {
625
        $options = [];
1,773✔
626
        if (isset($context[self::GROUPS])) {
1,773✔
627
            /* @see https://github.com/symfony/symfony/blob/v4.2.6/src/Symfony/Component/PropertyInfo/Extractor/SerializerExtractor.php */
628
            $options['serializer_groups'] = (array) $context[self::GROUPS];
609✔
629
        }
630

631
        $operationCacheKey = ($context['resource_class'] ?? '').($context['operation_name'] ?? '').($context['root_operation_name'] ?? '');
1,773✔
632
        $suffix = ($context['api_normalize'] ?? '') ? 'n' : '';
1,773✔
633
        if ($operationCacheKey && isset($this->localFactoryOptionsCache[$operationCacheKey.$suffix])) {
1,773✔
634
            return $options + $this->localFactoryOptionsCache[$operationCacheKey.$suffix];
1,757✔
635
        }
636

637
        // This is a hot spot
638
        if (isset($context['resource_class'])) {
1,773✔
639
            // Note that the groups need to be read on the root operation
640
            if ($operation = ($context['root_operation'] ?? null)) {
1,773✔
641
                $options['normalization_groups'] = $operation->getNormalizationContext()['groups'] ?? null;
751✔
642
                $options['denormalization_groups'] = $operation->getDenormalizationContext()['groups'] ?? null;
751✔
643
                $options['operation_name'] = $operation->getName();
751✔
644
            }
645
        }
646

647
        return $options + $this->localFactoryOptionsCache[$operationCacheKey.$suffix] = $options;
1,773✔
648
    }
649

650
    /**
651
     * {@inheritdoc}
652
     *
653
     * @throws UnexpectedValueException
654
     */
655
    protected function getAttributeValue(object $object, string $attribute, ?string $format = null, array $context = []): mixed
656
    {
657
        $context['api_attribute'] = $attribute;
1,731✔
658
        $context['property_metadata'] = $propertyMetadata = $this->propertyMetadataFactory->create($context['resource_class'], $attribute, $this->getFactoryOptions($context));
1,731✔
659

660
        if ($context['api_denormalize'] ?? false) {
1,731✔
661
            return $this->propertyAccessor->getValue($object, $attribute);
21✔
662
        }
663

664
        $types = $propertyMetadata->getBuiltinTypes() ?? [];
1,731✔
665

666
        foreach ($types as $type) {
1,731✔
667
            if (
668
                $type->isCollection()
1,699✔
669
                && ($collectionValueType = $type->getCollectionValueTypes()[0] ?? null)
1,699✔
670
                && ($className = $collectionValueType->getClassName())
1,699✔
671
                && $this->resourceClassResolver->isResourceClass($className)
1,699✔
672
            ) {
673
                $childContext = $this->createChildContext($this->createOperationContext($context, $className), $attribute, $format);
433✔
674

675
                // @see ApiPlatform\Hal\Serializer\ItemNormalizer:getComponents logic for intentional duplicate content
676
                // @see ApiPlatform\JsonApi\Serializer\ItemNormalizer:getComponents logic for intentional duplicate content
677
                if ('jsonld' === $format && $itemUriTemplate = $propertyMetadata->getUriTemplate()) {
433✔
678
                    $operation = $this->resourceMetadataCollectionFactory->create($className)->getOperation(
2✔
679
                        operationName: $itemUriTemplate,
2✔
680
                        forceCollection: true,
2✔
681
                        httpOperation: true
2✔
682
                    );
2✔
683

684
                    return $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_PATH, $operation, $childContext);
2✔
685
                }
686

687
                $attributeValue = $this->propertyAccessor->getValue($object, $attribute);
431✔
688

689
                if (!is_iterable($attributeValue)) {
431✔
690
                    throw new UnexpectedValueException('Unexpected non-iterable value for to-many relation.');
×
691
                }
692

693
                $resourceClass = $this->resourceClassResolver->getResourceClass($attributeValue, $className);
431✔
694

695
                $data = $this->normalizeCollectionOfRelations($propertyMetadata, $attributeValue, $resourceClass, $format, $childContext);
431✔
696
                $context['data'] = $data;
431✔
697
                $context['type'] = $type;
431✔
698

699
                if ($this->tagCollector) {
431✔
700
                    $this->tagCollector->collect($context);
392✔
701
                }
702

703
                return $data;
431✔
704
            }
705

706
            if (
707
                ($className = $type->getClassName())
1,699✔
708
                && $this->resourceClassResolver->isResourceClass($className)
1,699✔
709
            ) {
710
                $childContext = $this->createChildContext($this->createOperationContext($context, $className), $attribute, $format);
607✔
711
                unset($childContext['iri'], $childContext['uri_variables'], $childContext['item_uri_template']);
607✔
712
                if ('jsonld' === $format && $uriTemplate = $propertyMetadata->getUriTemplate()) {
607✔
713
                    $operation = $this->resourceMetadataCollectionFactory->create($className)->getOperation(
2✔
714
                        operationName: $uriTemplate,
2✔
715
                        httpOperation: true
2✔
716
                    );
2✔
717

718
                    return $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_PATH, $operation, $childContext);
2✔
719
                }
720

721
                $attributeValue = $this->propertyAccessor->getValue($object, $attribute);
605✔
722

723
                if (!\is_object($attributeValue) && null !== $attributeValue) {
601✔
724
                    throw new UnexpectedValueException('Unexpected non-object value for to-one relation.');
×
725
                }
726

727
                $resourceClass = $this->resourceClassResolver->getResourceClass($attributeValue, $className);
601✔
728

729
                $data = $this->normalizeRelation($propertyMetadata, $attributeValue, $resourceClass, $format, $childContext);
601✔
730
                $context['data'] = $data;
601✔
731
                $context['type'] = $type;
601✔
732

733
                if ($this->tagCollector) {
601✔
734
                    $this->tagCollector->collect($context);
560✔
735
                }
736

737
                return $data;
601✔
738
            }
739

740
            if (!$this->serializer instanceof NormalizerInterface) {
1,685✔
741
                throw new LogicException(\sprintf('The injected serializer must be an instance of "%s".', NormalizerInterface::class));
×
742
            }
743

744
            unset(
1,685✔
745
                $context['resource_class'],
1,685✔
746
                $context['force_resource_class'],
1,685✔
747
                $context['uri_variables'],
1,685✔
748
            );
1,685✔
749

750
            // Anonymous resources
751
            if ($className) {
1,685✔
752
                $childContext = $this->createChildContext($this->createOperationContext($context, $className), $attribute, $format);
534✔
753
                $childContext['output']['gen_id'] = $propertyMetadata->getGenId() ?? true;
534✔
754

755
                $attributeValue = $this->propertyAccessor->getValue($object, $attribute);
534✔
756

757
                return $this->serializer->normalize($attributeValue, $format, $childContext);
528✔
758
            }
759

760
            if ('array' === $type->getBuiltinType()) {
1,666✔
761
                if ($className = ($type->getCollectionValueTypes()[0] ?? null)?->getClassName()) {
415✔
762
                    $context = $this->createOperationContext($context, $className);
12✔
763
                }
764

765
                $childContext = $this->createChildContext($context, $attribute, $format);
415✔
766
                $childContext['output']['gen_id'] = $propertyMetadata->getGenId() ?? true;
415✔
767

768
                $attributeValue = $this->propertyAccessor->getValue($object, $attribute);
415✔
769

770
                return $this->serializer->normalize($attributeValue, $format, $childContext);
415✔
771
            }
772
        }
773

774
        if (!$this->serializer instanceof NormalizerInterface) {
1,696✔
775
            throw new LogicException(\sprintf('The injected serializer must be an instance of "%s".', NormalizerInterface::class));
×
776
        }
777

778
        unset(
1,696✔
779
            $context['resource_class'],
1,696✔
780
            $context['force_resource_class'],
1,696✔
781
            $context['uri_variables']
1,696✔
782
        );
1,696✔
783

784
        $attributeValue = $this->propertyAccessor->getValue($object, $attribute);
1,696✔
785

786
        return $this->serializer->normalize($attributeValue, $format, $context);
1,693✔
787
    }
788

789
    /**
790
     * Normalizes a collection of relations (to-many).
791
     *
792
     * @throws UnexpectedValueException
793
     */
794
    protected function normalizeCollectionOfRelations(ApiProperty $propertyMetadata, iterable $attributeValue, string $resourceClass, ?string $format, array $context): array
795
    {
796
        $value = [];
392✔
797
        foreach ($attributeValue as $index => $obj) {
392✔
798
            if (!\is_object($obj) && null !== $obj) {
105✔
799
                throw new UnexpectedValueException('Unexpected non-object element in to-many relation.');
×
800
            }
801

802
            // update context, if concrete object class deviates from general relation class (e.g. in case of polymorphic resources)
803
            $objResourceClass = $this->resourceClassResolver->getResourceClass($obj, $resourceClass);
105✔
804
            $context['resource_class'] = $objResourceClass;
105✔
805
            if ($this->resourceMetadataCollectionFactory) {
105✔
806
                $context['operation'] = $this->resourceMetadataCollectionFactory->create($objResourceClass)->getOperation();
105✔
807
            }
808

809
            $value[$index] = $this->normalizeRelation($propertyMetadata, $obj, $resourceClass, $format, $context);
105✔
810
        }
811

812
        return $value;
392✔
813
    }
814

815
    /**
816
     * Normalizes a relation.
817
     *
818
     * @throws LogicException
819
     * @throws UnexpectedValueException
820
     */
821
    protected function normalizeRelation(ApiProperty $propertyMetadata, ?object $relatedObject, string $resourceClass, ?string $format, array $context): \ArrayObject|array|string|null
822
    {
823
        if (null === $relatedObject || !empty($context['attributes']) || $propertyMetadata->isReadableLink()) {
539✔
824
            if (!$this->serializer instanceof NormalizerInterface) {
419✔
825
                throw new LogicException(\sprintf('The injected serializer must be an instance of "%s".', NormalizerInterface::class));
×
826
            }
827

828
            $relatedContext = $this->createOperationContext($context, $resourceClass);
419✔
829
            $normalizedRelatedObject = $this->serializer->normalize($relatedObject, $format, $relatedContext);
419✔
830
            if (!\is_string($normalizedRelatedObject) && !\is_array($normalizedRelatedObject) && !$normalizedRelatedObject instanceof \ArrayObject && null !== $normalizedRelatedObject) {
419✔
831
                throw new UnexpectedValueException('Expected normalized relation to be an IRI, array, \ArrayObject or null');
×
832
            }
833

834
            return $normalizedRelatedObject;
419✔
835
        }
836

837
        $context['iri'] = $iri = $this->iriConverter->getIriFromResource(resource: $relatedObject, context: $context);
178✔
838
        $context['data'] = $iri;
178✔
839
        $context['object'] = $relatedObject;
178✔
840
        unset($context['property_metadata'], $context['api_attribute']);
178✔
841

842
        if ($this->tagCollector) {
178✔
843
            $this->tagCollector->collect($context);
174✔
844
        } elseif (isset($context['resources'])) {
4✔
845
            $context['resources'][$iri] = $iri;
×
846
        }
847

848
        $push = $propertyMetadata->getPush() ?? false;
178✔
849
        if (isset($context['resources_to_push']) && $push) {
178✔
850
            $context['resources_to_push'][$iri] = $iri;
17✔
851
        }
852

853
        return $iri;
178✔
854
    }
855

856
    private function createAttributeValue(string $attribute, mixed $value, ?string $format = null, array &$context = []): mixed
857
    {
858
        try {
859
            return $this->createAndValidateAttributeValue($attribute, $value, $format, $context);
393✔
860
        } catch (NotNormalizableValueException $exception) {
30✔
861
            if (!isset($context['not_normalizable_value_exceptions'])) {
20✔
862
                throw $exception;
19✔
863
            }
864
            $context['not_normalizable_value_exceptions'][] = $exception;
1✔
865

866
            throw $exception;
1✔
867
        }
868
    }
869

870
    private function createAndValidateAttributeValue(string $attribute, mixed $value, ?string $format = null, array $context = []): mixed
871
    {
872
        $propertyMetadata = $this->propertyMetadataFactory->create($context['resource_class'], $attribute, $this->getFactoryOptions($context));
415✔
873
        $types = $propertyMetadata->getBuiltinTypes() ?? [];
415✔
874
        $isMultipleTypes = \count($types) > 1;
415✔
875
        $denormalizationException = null;
415✔
876

877
        foreach ($types as $type) {
415✔
878
            if (null === $value && ($type->isNullable() || ($context[static::DISABLE_TYPE_ENFORCEMENT] ?? false))) {
407✔
879
                return $value;
5✔
880
            }
881

882
            $collectionValueType = $type->getCollectionValueTypes()[0] ?? null;
406✔
883

884
            /* From @see AbstractObjectNormalizer::validateAndDenormalize() */
885
            // Fix a collection that contains the only one element
886
            // This is special to xml format only
887
            if ('xml' === $format && null !== $collectionValueType && (!\is_array($value) || !\is_int(key($value)))) {
406✔
888
                $value = [$value];
2✔
889
            }
890

891
            if (
892
                $type->isCollection()
406✔
893
                && null !== $collectionValueType
406✔
894
                && null !== ($className = $collectionValueType->getClassName())
406✔
895
                && $this->resourceClassResolver->isResourceClass($className)
406✔
896
            ) {
897
                $resourceClass = $this->resourceClassResolver->getResourceClass(null, $className);
31✔
898
                $context['resource_class'] = $resourceClass;
31✔
899
                unset($context['uri_variables']);
31✔
900

901
                try {
902
                    return $this->denormalizeCollection($attribute, $propertyMetadata, $type, $resourceClass, $value, $format, $context);
31✔
903
                } catch (NotNormalizableValueException $e) {
5✔
904
                    // union/intersect types: try the next type, if not valid, an exception will be thrown at the end
905
                    if ($isMultipleTypes) {
5✔
906
                        $denormalizationException ??= $e;
×
907

908
                        continue;
×
909
                    }
910

911
                    throw $e;
5✔
912
                }
913
            }
914

915
            if (
916
                null !== ($className = $type->getClassName())
397✔
917
                && $this->resourceClassResolver->isResourceClass($className)
397✔
918
            ) {
919
                $resourceClass = $this->resourceClassResolver->getResourceClass(null, $className);
107✔
920
                $childContext = $this->createChildContext($this->createOperationContext($context, $resourceClass), $attribute, $format);
107✔
921

922
                try {
923
                    return $this->denormalizeRelation($attribute, $propertyMetadata, $resourceClass, $value, $format, $childContext);
107✔
924
                } catch (NotNormalizableValueException $e) {
14✔
925
                    // union/intersect types: try the next type, if not valid, an exception will be thrown at the end
926
                    if ($isMultipleTypes) {
4✔
927
                        $denormalizationException ??= $e;
×
928

929
                        continue;
×
930
                    }
931

932
                    throw $e;
4✔
933
                }
934
            }
935

936
            if (
937
                $type->isCollection()
360✔
938
                && null !== $collectionValueType
360✔
939
                && null !== ($className = $collectionValueType->getClassName())
360✔
940
                && \is_array($value)
360✔
941
            ) {
942
                if (!$this->serializer instanceof DenormalizerInterface) {
6✔
943
                    throw new LogicException(\sprintf('The injected serializer must be an instance of "%s".', DenormalizerInterface::class));
×
944
                }
945

946
                unset($context['resource_class'], $context['uri_variables']);
6✔
947

948
                try {
949
                    return $this->serializer->denormalize($value, $className.'[]', $format, $context);
6✔
950
                } catch (NotNormalizableValueException $e) {
×
951
                    // union/intersect types: try the next type, if not valid, an exception will be thrown at the end
952
                    if ($isMultipleTypes) {
×
953
                        $denormalizationException ??= $e;
×
954

955
                        continue;
×
956
                    }
957

958
                    throw $e;
×
959
                }
960
            }
961

962
            if (null !== $className = $type->getClassName()) {
359✔
963
                if (!$this->serializer instanceof DenormalizerInterface) {
34✔
964
                    throw new LogicException(\sprintf('The injected serializer must be an instance of "%s".', DenormalizerInterface::class));
×
965
                }
966

967
                unset($context['resource_class'], $context['uri_variables']);
34✔
968

969
                try {
970
                    return $this->serializer->denormalize($value, $className, $format, $context);
34✔
971
                } catch (NotNormalizableValueException $e) {
9✔
972
                    // union/intersect types: try the next type, if not valid, an exception will be thrown at the end
973
                    if ($isMultipleTypes) {
9✔
974
                        $denormalizationException ??= $e;
2✔
975

976
                        continue;
2✔
977
                    }
978

979
                    throw $e;
7✔
980
                }
981
            }
982

983
            /* From @see AbstractObjectNormalizer::validateAndDenormalize() */
984
            // In XML and CSV all basic datatypes are represented as strings, it is e.g. not possible to determine,
985
            // if a value is meant to be a string, float, int or a boolean value from the serialized representation.
986
            // That's why we have to transform the values, if one of these non-string basic datatypes is expected.
987
            if (\is_string($value) && (XmlEncoder::FORMAT === $format || CsvEncoder::FORMAT === $format)) {
346✔
988
                if ('' === $value && $type->isNullable() && \in_array($type->getBuiltinType(), [Type::BUILTIN_TYPE_BOOL, Type::BUILTIN_TYPE_INT, Type::BUILTIN_TYPE_FLOAT], true)) {
30✔
989
                    return null;
×
990
                }
991

992
                switch ($type->getBuiltinType()) {
30✔
993
                    case Type::BUILTIN_TYPE_BOOL:
30✔
994
                        // according to http://www.w3.org/TR/xmlschema-2/#boolean, valid representations are "false", "true", "0" and "1"
995
                        if ('false' === $value || '0' === $value) {
8✔
996
                            $value = false;
4✔
997
                        } elseif ('true' === $value || '1' === $value) {
4✔
998
                            $value = true;
4✔
999
                        } else {
1000
                            // union/intersect types: try the next type, if not valid, an exception will be thrown at the end
1001
                            if ($isMultipleTypes) {
×
1002
                                break 2;
×
1003
                            }
1004
                            throw NotNormalizableValueException::createForUnexpectedDataType(\sprintf('The type of the "%s" attribute for class "%s" must be bool ("%s" given).', $attribute, $className, $value), $value, [Type::BUILTIN_TYPE_BOOL], $context['deserialization_path'] ?? null);
×
1005
                        }
1006
                        break;
8✔
1007
                    case Type::BUILTIN_TYPE_INT:
22✔
1008
                        if (ctype_digit($value) || ('-' === $value[0] && ctype_digit(substr($value, 1)))) {
8✔
1009
                            $value = (int) $value;
8✔
1010
                        } else {
1011
                            // union/intersect types: try the next type, if not valid, an exception will be thrown at the end
1012
                            if ($isMultipleTypes) {
×
1013
                                break 2;
×
1014
                            }
1015
                            throw NotNormalizableValueException::createForUnexpectedDataType(\sprintf('The type of the "%s" attribute for class "%s" must be int ("%s" given).', $attribute, $className, $value), $value, [Type::BUILTIN_TYPE_INT], $context['deserialization_path'] ?? null);
×
1016
                        }
1017
                        break;
8✔
1018
                    case Type::BUILTIN_TYPE_FLOAT:
14✔
1019
                        if (is_numeric($value)) {
8✔
1020
                            return (float) $value;
2✔
1021
                        }
1022

1023
                        switch ($value) {
1024
                            case 'NaN':
6✔
1025
                                return \NAN;
2✔
1026
                            case 'INF':
4✔
1027
                                return \INF;
2✔
1028
                            case '-INF':
2✔
1029
                                return -\INF;
2✔
1030
                            default:
1031
                                // union/intersect types: try the next type, if not valid, an exception will be thrown at the end
1032
                                if ($isMultipleTypes) {
×
1033
                                    break 3;
×
1034
                                }
1035
                                throw NotNormalizableValueException::createForUnexpectedDataType(\sprintf('The type of the "%s" attribute for class "%s" must be float ("%s" given).', $attribute, $className, $value), $value, [Type::BUILTIN_TYPE_FLOAT], $context['deserialization_path'] ?? null);
×
1036
                        }
1037
                }
1038
            }
1039

1040
            if ($context[static::DISABLE_TYPE_ENFORCEMENT] ?? false) {
338✔
1041
                return $value;
×
1042
            }
1043

1044
            try {
1045
                $this->validateType($attribute, $type, $value, $format, $context);
338✔
1046

1047
                break;
330✔
1048
            } catch (NotNormalizableValueException $e) {
14✔
1049
                // union/intersect types: try the next type
1050
                if (!$isMultipleTypes) {
14✔
1051
                    throw $e;
8✔
1052
                }
1053
            }
1054
        }
1055

1056
        if ($denormalizationException) {
338✔
1057
            throw $denormalizationException;
2✔
1058
        }
1059

1060
        return $value;
338✔
1061
    }
1062

1063
    /**
1064
     * Sets a value of the object using the PropertyAccess component.
1065
     */
1066
    private function setValue(object $object, string $attributeName, mixed $value): void
1067
    {
1068
        try {
1069
            $this->propertyAccessor->setValue($object, $attributeName, $value);
374✔
1070
        } catch (NoSuchPropertyException) {
17✔
1071
            // Properties not found are ignored
1072
        }
1073
    }
1074
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc