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

api-platform / core / 14008635868

22 Mar 2025 12:39PM UTC coverage: 8.52% (+0.005%) from 8.515%
14008635868

Pull #7042

github

web-flow
Merge fdd88ef56 into 47a6dffbb
Pull Request #7042: Purge parent collections in inheritance cases

4 of 9 new or added lines in 1 file covered. (44.44%)

540 existing lines in 57 files now uncovered.

13394 of 157210 relevant lines covered (8.52%)

22.93 hits per line

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

85.38
/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
use Symfony\Component\Serializer\Serializer;
46

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

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

65
    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)
66
    {
67
        if (!isset($defaultContext['circular_reference_handler'])) {
2,022✔
68
            $defaultContext['circular_reference_handler'] = fn ($object): ?string => $this->iriConverter->getIriFromResource($object);
2,010✔
69
        }
70

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

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

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

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

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

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

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

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

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

128
        if ($this->resourceClassResolver->isResourceClass($resourceClass)) {
1,724✔
129
            $context = $this->initContext($resourceClass, $context);
1,684✔
130
        }
131

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

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

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

152
        $context['object'] = $object;
1,724✔
153
        $context['format'] = $format;
1,724✔
154

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

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

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

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

167
            return $iri;
×
168
        }
169

170
        if ($this->tagCollector) {
1,724✔
171
            $this->tagCollector->collect($context);
1,507✔
172
        }
173

174
        return $data;
1,724✔
175
    }
176

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

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

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

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

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

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

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

216
        $context['api_denormalize'] = true;
461✔
217

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

223
        if (\is_string($data)) {
461✔
224
            try {
225
                return $this->iriConverter->getResourceFromIri($data, $context + ['fetch_data' => true]);
5✔
226
            } catch (ItemNotFoundException $e) {
×
227
                throw new UnexpectedValueException($e->getMessage(), $e->getCode(), $e);
×
228
            } catch (InvalidArgumentException $e) {
×
229
                throw new UnexpectedValueException(\sprintf('Invalid IRI "%s".', $data), $e->getCode(), $e);
×
230
            }
231
        }
232

233
        if (!\is_array($data)) {
457✔
234
            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✔
235
        }
236

237
        $previousObject = $this->clone($objectToPopulate);
457✔
238
        $object = parent::denormalize($data, $class, $format, $context);
457✔
239

240
        if (!$this->resourceClassResolver->isResourceClass($class)) {
427✔
241
            return $object;
×
242
        }
243

244
        // Bypass the post-denormalize attribute revert logic if the object could not be
245
        // cloned since we cannot possibly revert any changes made to it.
246
        if (null !== $objectToPopulate && null === $previousObject) {
427✔
247
            return $object;
×
248
        }
249

250
        $options = $this->getFactoryOptions($context);
427✔
251
        $propertyNames = iterator_to_array($this->propertyNameCollectionFactory->create($resourceClass, $options));
427✔
252

253
        // Revert attributes that aren't allowed to be changed after a post-denormalize check
254
        foreach (array_keys($data) as $attribute) {
427✔
255
            $attribute = $this->nameConverter ? $this->nameConverter->denormalize((string) $attribute) : $attribute;
409✔
256
            if (!\in_array($attribute, $propertyNames, true)) {
409✔
257
                continue;
90✔
258
            }
259

260
            if (!$this->canAccessAttributePostDenormalize($object, $previousObject, $attribute, $context)) {
388✔
261
                if (null !== $previousObject) {
4✔
UNCOV
262
                    $this->setValue($object, $attribute, $this->propertyAccessor->getValue($previousObject, $attribute));
1✔
263
                } else {
264
                    $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $attribute, $options);
3✔
265
                    $this->setValue($object, $attribute, $propertyMetadata->getDefault());
3✔
266
                }
267
            }
268
        }
269

270
        return $object;
427✔
271
    }
272

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

286
            return $object;
97✔
287
        }
288

289
        $class = $this->getClassDiscriminatorResolvedClass($data, $class, $context);
374✔
290
        $reflectionClass = new \ReflectionClass($class);
374✔
291

292
        $constructor = $this->getConstructor($data, $class, $context, $reflectionClass, $allowedAttributes);
374✔
293
        if ($constructor) {
374✔
294
            $constructorParameters = $constructor->getParameters();
171✔
295

296
            $params = [];
171✔
297
            $missingConstructorArguments = [];
171✔
298
            foreach ($constructorParameters as $constructorParameter) {
171✔
299
                $paramName = $constructorParameter->name;
77✔
300
                $key = $this->nameConverter ? $this->nameConverter->normalize($paramName, $class, $format, $context) : $paramName;
77✔
301
                $attributeContext = $this->getAttributeDenormalizationContext($class, $paramName, $context);
77✔
302
                $attributeContext['deserialization_path'] = $attributeContext['deserialization_path'] ?? $key;
77✔
303

304
                $allowed = false === $allowedAttributes || (\is_array($allowedAttributes) && \in_array($paramName, $allowedAttributes, true));
77✔
305
                $ignored = !$this->isAllowedAttribute($class, $paramName, $format, $context);
77✔
306
                if ($constructorParameter->isVariadic()) {
77✔
307
                    if ($allowed && !$ignored && (isset($data[$key]) || \array_key_exists($key, $data))) {
×
308
                        if (!\is_array($data[$paramName])) {
×
309
                            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));
×
310
                        }
311

312
                        $params[] = $data[$paramName];
×
313
                    }
314
                } elseif ($allowed && !$ignored && (isset($data[$key]) || \array_key_exists($key, $data))) {
77✔
315
                    try {
316
                        $params[] = $this->createConstructorArgument($data[$key], $key, $constructorParameter, $attributeContext, $format);
23✔
317
                    } catch (NotNormalizableValueException $exception) {
4✔
318
                        if (!isset($context['not_normalizable_value_exceptions'])) {
4✔
319
                            throw $exception;
3✔
320
                        }
UNCOV
321
                        $context['not_normalizable_value_exceptions'][] = $exception;
1✔
322
                    }
323

324
                    // Don't run set for a parameter passed to the constructor
325
                    unset($data[$key]);
20✔
326
                } elseif (isset($context[static::DEFAULT_CONSTRUCTOR_ARGUMENTS][$class][$key])) {
68✔
327
                    $params[] = $context[static::DEFAULT_CONSTRUCTOR_ARGUMENTS][$class][$key];
×
328
                } elseif ($constructorParameter->isDefaultValueAvailable()) {
68✔
329
                    $params[] = $constructorParameter->getDefaultValue();
67✔
330
                } else {
331
                    if (!isset($context['not_normalizable_value_exceptions'])) {
3✔
332
                        $missingConstructorArguments[] = $constructorParameter->name;
2✔
333
                    }
334

335
                    $constructorParameterType = 'unknown';
3✔
336
                    $reflectionType = $constructorParameter->getType();
3✔
337
                    if ($reflectionType instanceof \ReflectionNamedType) {
3✔
338
                        $constructorParameterType = $reflectionType->getName();
3✔
339
                    }
340

341
                    $exception = NotNormalizableValueException::createForUnexpectedDataType(
3✔
342
                        \sprintf('Failed to create object because the class misses the "%s" property.', $constructorParameter->name),
3✔
343
                        null,
3✔
344
                        [$constructorParameterType],
3✔
345
                        $attributeContext['deserialization_path'],
3✔
346
                        true
3✔
347
                    );
3✔
348
                    $context['not_normalizable_value_exceptions'][] = $exception;
3✔
349
                }
350
            }
351

352
            if ($missingConstructorArguments) {
168✔
353
                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✔
354
            }
355

356
            if (\count($context['not_normalizable_value_exceptions'] ?? []) > 0) {
168✔
UNCOV
357
                return $reflectionClass->newInstanceWithoutConstructor();
1✔
358
            }
359

360
            if ($constructor->isConstructor()) {
167✔
361
                return $reflectionClass->newInstanceArgs($params);
167✔
362
            }
363

364
            return $constructor->invokeArgs(null, $params);
×
365
        }
366

367
        return new $class();
214✔
368
    }
369

370
    protected function getClassDiscriminatorResolvedClass(array $data, string $class, array $context = []): string
371
    {
372
        if (null === $this->classDiscriminatorResolver || (null === $mapping = $this->classDiscriminatorResolver->getMappingForClass($class))) {
378✔
373
            return $class;
378✔
374
        }
375

376
        if (!isset($data[$mapping->getTypeProperty()])) {
2✔
377
            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());
×
378
        }
379

380
        $type = $data[$mapping->getTypeProperty()];
2✔
381
        if (null === ($mappedClass = $mapping->getClassForType($type))) {
2✔
382
            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);
×
383
        }
384

385
        return $mappedClass;
2✔
386
    }
387

388
    protected function createConstructorArgument($parameterData, string $key, \ReflectionParameter $constructorParameter, array $context, ?string $format = null): mixed
389
    {
390
        return $this->createAndValidateAttributeValue($constructorParameter->name, $parameterData, $format, $context);
23✔
391
    }
392

393
    /**
394
     * {@inheritdoc}
395
     *
396
     * Unused in this context.
397
     *
398
     * @return string[]
399
     */
400
    protected function extractAttributes($object, $format = null, array $context = []): array
401
    {
402
        return [];
×
403
    }
404

405
    /**
406
     * {@inheritdoc}
407
     */
408
    protected function getAllowedAttributes(string|object $classOrObject, array $context, bool $attributesAsString = false): array|bool
409
    {
410
        if (!$this->resourceClassResolver->isResourceClass($context['resource_class'])) {
1,738✔
411
            return parent::getAllowedAttributes($classOrObject, $context, $attributesAsString);
43✔
412
        }
413

414
        $resourceClass = $this->resourceClassResolver->getResourceClass(null, $context['resource_class']); // fix for abstract classes and interfaces
1,700✔
415
        $options = $this->getFactoryOptions($context);
1,700✔
416
        $propertyNames = $this->propertyNameCollectionFactory->create($resourceClass, $options);
1,700✔
417

418
        $allowedAttributes = [];
1,700✔
419
        foreach ($propertyNames as $propertyName) {
1,700✔
420
            $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $propertyName, $options);
1,686✔
421

422
            if (
423
                $this->isAllowedAttribute($classOrObject, $propertyName, null, $context)
1,686✔
424
                && (isset($context['api_normalize']) && $propertyMetadata->isReadable()
1,686✔
425
                    || isset($context['api_denormalize']) && ($propertyMetadata->isWritable() || !\is_object($classOrObject) && $propertyMetadata->isInitializable())
1,686✔
426
                )
427
            ) {
428
                $allowedAttributes[] = $propertyName;
1,672✔
429
            }
430
        }
431

432
        return $allowedAttributes;
1,700✔
433
    }
434

435
    /**
436
     * {@inheritdoc}
437
     */
438
    protected function isAllowedAttribute(object|string $classOrObject, string $attribute, ?string $format = null, array $context = []): bool
439
    {
440
        if (!parent::isAllowedAttribute($classOrObject, $attribute, $format, $context)) {
1,724✔
441
            return false;
438✔
442
        }
443

444
        return $this->canAccessAttribute(\is_object($classOrObject) ? $classOrObject : null, $attribute, $context);
1,722✔
445
    }
446

447
    /**
448
     * Check if access to the attribute is granted.
449
     */
450
    protected function canAccessAttribute(?object $object, string $attribute, array $context = []): bool
451
    {
452
        if (!$this->resourceClassResolver->isResourceClass($context['resource_class'])) {
1,722✔
453
            return true;
43✔
454
        }
455

456
        $options = $this->getFactoryOptions($context);
1,684✔
457
        $propertyMetadata = $this->propertyMetadataFactory->create($context['resource_class'], $attribute, $options);
1,684✔
458
        $security = $propertyMetadata->getSecurity() ?? $propertyMetadata->getPolicy();
1,684✔
459
        if (null !== $this->resourceAccessChecker && $security) {
1,684✔
460
            return $this->resourceAccessChecker->isGranted($context['resource_class'], $security, [
62✔
461
                'object' => $object,
62✔
462
                'property' => $attribute,
62✔
463
            ]);
62✔
464
        }
465

466
        return true;
1,676✔
467
    }
468

469
    /**
470
     * Check if access to the attribute is granted.
471
     */
472
    protected function canAccessAttributePostDenormalize(?object $object, ?object $previousObject, string $attribute, array $context = []): bool
473
    {
474
        $options = $this->getFactoryOptions($context);
388✔
475
        $propertyMetadata = $this->propertyMetadataFactory->create($context['resource_class'], $attribute, $options);
388✔
476
        $security = $propertyMetadata->getSecurityPostDenormalize();
388✔
477
        if ($this->resourceAccessChecker && $security) {
388✔
478
            return $this->resourceAccessChecker->isGranted($context['resource_class'], $security, [
10✔
479
                'object' => $object,
10✔
480
                'previous_object' => $previousObject,
10✔
481
                'property' => $attribute,
10✔
482
            ]);
10✔
483
        }
484

485
        return true;
386✔
486
    }
487

488
    /**
489
     * {@inheritdoc}
490
     */
491
    protected function setAttributeValue(object $object, string $attribute, mixed $value, ?string $format = null, array $context = []): void
492
    {
493
        try {
494
            $this->setValue($object, $attribute, $this->createAttributeValue($attribute, $value, $format, $context));
389✔
495
        } catch (NotNormalizableValueException $exception) {
28✔
496
            // Only throw if collecting denormalization errors is disabled.
497
            if (!isset($context['not_normalizable_value_exceptions'])) {
20✔
498
                throw $exception;
19✔
499
            }
500
        }
501
    }
502

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

517
        if (!$isValid) {
338✔
518
            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✔
519
        }
520
    }
521

522
    /**
523
     * Denormalizes a collection of objects.
524
     *
525
     * @throws NotNormalizableValueException
526
     */
527
    protected function denormalizeCollection(string $attribute, ApiProperty $propertyMetadata, Type $type, string $className, mixed $value, ?string $format, array $context): array
528
    {
529
        if (!\is_array($value)) {
31✔
530
            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✔
531
        }
532

533
        $values = [];
28✔
534
        $childContext = $this->createChildContext($this->createOperationContext($context, $className), $attribute, $format);
28✔
535
        $collectionKeyTypes = $type->getCollectionKeyTypes();
28✔
536
        foreach ($value as $index => $obj) {
28✔
537
            $currentChildContext = $childContext;
28✔
538
            if (isset($childContext['deserialization_path'])) {
28✔
539
                $currentChildContext['deserialization_path'] = "{$childContext['deserialization_path']}[{$index}]";
28✔
540
            }
541

542
            // no typehint provided on collection key
543
            if (!$collectionKeyTypes) {
28✔
544
                $values[$index] = $this->denormalizeRelation($attribute, $propertyMetadata, $className, $obj, $format, $currentChildContext);
×
545
                continue;
×
546
            }
547

548
            // validate collection key typehint
549
            foreach ($collectionKeyTypes as $collectionKeyType) {
28✔
550
                $collectionKeyBuiltinType = $collectionKeyType->getBuiltinType();
28✔
551
                if (!\call_user_func('is_'.$collectionKeyBuiltinType, $index)) {
28✔
552
                    continue;
2✔
553
                }
554

555
                $values[$index] = $this->denormalizeRelation($attribute, $propertyMetadata, $className, $obj, $format, $currentChildContext);
26✔
556
                continue 2;
26✔
557
            }
558
            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✔
559
        }
560

561
        return $values;
26✔
562
    }
563

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

590
                return null;
×
591
            } catch (InvalidArgumentException $e) {
4✔
592
                if (!isset($context['not_normalizable_value_exceptions'])) {
4✔
593
                    throw new UnexpectedValueException(\sprintf('Invalid IRI "%s".', $value), $e->getCode(), $e);
4✔
594
                }
595
                $context['not_normalizable_value_exceptions'][] = NotNormalizableValueException::createForUnexpectedDataType(
×
596
                    $e->getMessage(),
×
597
                    $value,
×
598
                    [$className],
×
599
                    $context['deserialization_path'] ?? null,
×
600
                    true,
×
601
                    $e->getCode(),
×
602
                    $e
×
603
                );
×
604

605
                return null;
×
606
            }
607
        }
608

609
        if ($propertyMetadata->isWritableLink()) {
51✔
610
            $context['api_allow_update'] = true;
49✔
611

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

616
            $item = $this->serializer->denormalize($value, $className, $format, $context);
49✔
617
            if (!\is_object($item) && null !== $item) {
45✔
618
                throw new \UnexpectedValueException('Expected item to be an object or null.');
×
619
            }
620

621
            return $item;
45✔
622
        }
623

UNCOV
624
        if (!\is_array($value)) {
2✔
UNCOV
625
            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✔
626
        }
627

UNCOV
628
        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✔
629
    }
630

631
    /**
632
     * Gets the options for the property name collection / property metadata factories.
633
     */
634
    protected function getFactoryOptions(array $context): array
635
    {
636
        $options = [];
1,738✔
637
        if (isset($context[self::GROUPS])) {
1,738✔
638
            /* @see https://github.com/symfony/symfony/blob/v4.2.6/src/Symfony/Component/PropertyInfo/Extractor/SerializerExtractor.php */
639
            $options['serializer_groups'] = (array) $context[self::GROUPS];
591✔
640
        }
641

642
        $operationCacheKey = ($context['resource_class'] ?? '').($context['operation_name'] ?? '').($context['root_operation_name'] ?? '');
1,738✔
643
        $suffix = ($context['api_normalize'] ?? '') ? 'n' : '';
1,738✔
644
        if ($operationCacheKey && isset($this->localFactoryOptionsCache[$operationCacheKey.$suffix])) {
1,738✔
645
            return $options + $this->localFactoryOptionsCache[$operationCacheKey.$suffix];
1,722✔
646
        }
647

648
        // This is a hot spot
649
        if (isset($context['resource_class'])) {
1,738✔
650
            // Note that the groups need to be read on the root operation
651
            if ($operation = ($context['root_operation'] ?? null)) {
1,738✔
652
                $options['normalization_groups'] = $operation->getNormalizationContext()['groups'] ?? null;
737✔
653
                $options['denormalization_groups'] = $operation->getDenormalizationContext()['groups'] ?? null;
737✔
654
                $options['operation_name'] = $operation->getName();
737✔
655
            }
656
        }
657

658
        return $options + $this->localFactoryOptionsCache[$operationCacheKey.$suffix] = $options;
1,738✔
659
    }
660

661
    /**
662
     * {@inheritdoc}
663
     *
664
     * @throws UnexpectedValueException
665
     */
666
    protected function getAttributeValue(object $object, string $attribute, ?string $format = null, array $context = []): mixed
667
    {
668
        $context['api_attribute'] = $attribute;
1,696✔
669
        $context['property_metadata'] = $propertyMetadata = $this->propertyMetadataFactory->create($context['resource_class'], $attribute, $this->getFactoryOptions($context));
1,696✔
670

671
        if ($context['api_denormalize'] ?? false) {
1,696✔
672
            return $this->propertyAccessor->getValue($object, $attribute);
21✔
673
        }
674

675
        $types = $propertyMetadata->getBuiltinTypes() ?? [];
1,696✔
676

677
        foreach ($types as $type) {
1,696✔
678
            if (
679
                $type->isCollection()
1,664✔
680
                && ($collectionValueType = $type->getCollectionValueTypes()[0] ?? null)
1,664✔
681
                && ($className = $collectionValueType->getClassName())
1,664✔
682
                && $this->resourceClassResolver->isResourceClass($className)
1,664✔
683
            ) {
684
                $childContext = $this->createChildContext($this->createOperationContext($context, $className), $attribute, $format);
431✔
685

686
                // @see ApiPlatform\Hal\Serializer\ItemNormalizer:getComponents logic for intentional duplicate content
687
                // @see ApiPlatform\JsonApi\Serializer\ItemNormalizer:getComponents logic for intentional duplicate content
688
                if ('jsonld' === $format && $itemUriTemplate = $propertyMetadata->getUriTemplate()) {
431✔
689
                    $operation = $this->resourceMetadataCollectionFactory->create($className)->getOperation(
2✔
690
                        operationName: $itemUriTemplate,
2✔
691
                        forceCollection: true,
2✔
692
                        httpOperation: true
2✔
693
                    );
2✔
694

695
                    return $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_PATH, $operation, $childContext);
2✔
696
                }
697

698
                $attributeValue = $this->propertyAccessor->getValue($object, $attribute);
429✔
699

700
                if (!is_iterable($attributeValue)) {
429✔
701
                    throw new UnexpectedValueException('Unexpected non-iterable value for to-many relation.');
×
702
                }
703

704
                $resourceClass = $this->resourceClassResolver->getResourceClass($attributeValue, $className);
429✔
705

706
                $data = $this->normalizeCollectionOfRelations($propertyMetadata, $attributeValue, $resourceClass, $format, $childContext);
429✔
707
                $context['data'] = $data;
429✔
708
                $context['type'] = $type;
429✔
709

710
                if ($this->tagCollector) {
429✔
711
                    $this->tagCollector->collect($context);
390✔
712
                }
713

714
                return $data;
429✔
715
            }
716

717
            if (
718
                ($className = $type->getClassName())
1,664✔
719
                && $this->resourceClassResolver->isResourceClass($className)
1,664✔
720
            ) {
721
                $childContext = $this->createChildContext($this->createOperationContext($context, $className), $attribute, $format);
603✔
722
                unset($childContext['iri'], $childContext['uri_variables'], $childContext['item_uri_template']);
603✔
723
                if ('jsonld' === $format && $uriTemplate = $propertyMetadata->getUriTemplate()) {
603✔
724
                    $operation = $this->resourceMetadataCollectionFactory->create($className)->getOperation(
2✔
725
                        operationName: $uriTemplate,
2✔
726
                        httpOperation: true
2✔
727
                    );
2✔
728

729
                    return $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_PATH, $operation, $childContext);
2✔
730
                }
731

732
                $attributeValue = $this->propertyAccessor->getValue($object, $attribute);
601✔
733

734
                if (!\is_object($attributeValue) && null !== $attributeValue) {
597✔
735
                    throw new UnexpectedValueException('Unexpected non-object value for to-one relation.');
×
736
                }
737

738
                $resourceClass = $this->resourceClassResolver->getResourceClass($attributeValue, $className);
597✔
739

740
                $data = $this->normalizeRelation($propertyMetadata, $attributeValue, $resourceClass, $format, $childContext);
597✔
741
                $context['data'] = $data;
597✔
742
                $context['type'] = $type;
597✔
743

744
                if ($this->tagCollector) {
597✔
745
                    $this->tagCollector->collect($context);
558✔
746
                }
747

748
                return $data;
597✔
749
            }
750

751
            if (!$this->serializer instanceof NormalizerInterface) {
1,650✔
752
                throw new LogicException(\sprintf('The injected serializer must be an instance of "%s".', NormalizerInterface::class));
×
753
            }
754

755
            unset(
1,650✔
756
                $context['resource_class'],
1,650✔
757
                $context['force_resource_class'],
1,650✔
758
                $context['uri_variables'],
1,650✔
759
            );
1,650✔
760

761
            // Anonymous resources
762
            if ($className) {
1,650✔
763
                $childContext = $this->createChildContext($this->createOperationContext($context, $className), $attribute, $format);
516✔
764
                $childContext['output']['gen_id'] = $propertyMetadata->getGenId() ?? true;
516✔
765

766
                $attributeValue = $this->propertyAccessor->getValue($object, $attribute);
516✔
767

768
                return $this->serializer->normalize($attributeValue, $format, $childContext);
510✔
769
            }
770

771
            if ('array' === $type->getBuiltinType()) {
1,633✔
772
                if ($className = ($type->getCollectionValueTypes()[0] ?? null)?->getClassName()) {
409✔
773
                    $context = $this->createOperationContext($context, $className);
12✔
774
                }
775

776
                $childContext = $this->createChildContext($context, $attribute, $format);
409✔
777
                $childContext['output']['gen_id'] = $propertyMetadata->getGenId() ?? true;
409✔
778

779
                $attributeValue = $this->propertyAccessor->getValue($object, $attribute);
409✔
780

781
                return $this->serializer->normalize($attributeValue, $format, $childContext);
409✔
782
            }
783
        }
784

785
        if (!$this->serializer instanceof NormalizerInterface) {
1,663✔
786
            throw new LogicException(\sprintf('The injected serializer must be an instance of "%s".', NormalizerInterface::class));
×
787
        }
788

789
        unset(
1,663✔
790
            $context['resource_class'],
1,663✔
791
            $context['force_resource_class'],
1,663✔
792
            $context['uri_variables']
1,663✔
793
        );
1,663✔
794

795
        $attributeValue = $this->propertyAccessor->getValue($object, $attribute);
1,663✔
796

797
        return $this->serializer->normalize($attributeValue, $format, $context);
1,660✔
798
    }
799

800
    /**
801
     * Normalizes a collection of relations (to-many).
802
     *
803
     * @throws UnexpectedValueException
804
     */
805
    protected function normalizeCollectionOfRelations(ApiProperty $propertyMetadata, iterable $attributeValue, string $resourceClass, ?string $format, array $context): array
806
    {
807
        $value = [];
390✔
808
        foreach ($attributeValue as $index => $obj) {
390✔
809
            if (!\is_object($obj) && null !== $obj) {
103✔
810
                throw new UnexpectedValueException('Unexpected non-object element in to-many relation.');
×
811
            }
812

813
            // update context, if concrete object class deviates from general relation class (e.g. in case of polymorphic resources)
814
            $objResourceClass = $this->resourceClassResolver->getResourceClass($obj, $resourceClass);
103✔
815
            $context['resource_class'] = $objResourceClass;
103✔
816
            if ($this->resourceMetadataCollectionFactory) {
103✔
817
                $context['operation'] = $this->resourceMetadataCollectionFactory->create($objResourceClass)->getOperation();
103✔
818
            }
819

820
            $value[$index] = $this->normalizeRelation($propertyMetadata, $obj, $resourceClass, $format, $context);
103✔
821
        }
822

823
        return $value;
390✔
824
    }
825

826
    /**
827
     * Normalizes a relation.
828
     *
829
     * @throws LogicException
830
     * @throws UnexpectedValueException
831
     */
832
    protected function normalizeRelation(ApiProperty $propertyMetadata, ?object $relatedObject, string $resourceClass, ?string $format, array $context): \ArrayObject|array|string|null
833
    {
834
        if (null === $relatedObject || !empty($context['attributes']) || $propertyMetadata->isReadableLink()) {
533✔
835
            if (!$this->serializer instanceof NormalizerInterface) {
417✔
836
                throw new LogicException(\sprintf('The injected serializer must be an instance of "%s".', NormalizerInterface::class));
×
837
            }
838

839
            $relatedContext = $this->createOperationContext($context, $resourceClass);
417✔
840
            $normalizedRelatedObject = $this->serializer->normalize($relatedObject, $format, $relatedContext);
417✔
841
            if (!\is_string($normalizedRelatedObject) && !\is_array($normalizedRelatedObject) && !$normalizedRelatedObject instanceof \ArrayObject && null !== $normalizedRelatedObject) {
417✔
842
                throw new UnexpectedValueException('Expected normalized relation to be an IRI, array, \ArrayObject or null');
×
843
            }
844

845
            return $normalizedRelatedObject;
417✔
846
        }
847

848
        $context['iri'] = $iri = $this->iriConverter->getIriFromResource(resource: $relatedObject, context: $context);
174✔
849
        $context['data'] = $iri;
174✔
850
        $context['object'] = $relatedObject;
174✔
851
        unset($context['property_metadata'], $context['api_attribute']);
174✔
852

853
        if ($this->tagCollector) {
174✔
854
            $this->tagCollector->collect($context);
170✔
855
        } elseif (isset($context['resources'])) {
4✔
856
            $context['resources'][$iri] = $iri;
×
857
        }
858

859
        $push = $propertyMetadata->getPush() ?? false;
174✔
860
        if (isset($context['resources_to_push']) && $push) {
174✔
UNCOV
861
            $context['resources_to_push'][$iri] = $iri;
17✔
862
        }
863

864
        return $iri;
174✔
865
    }
866

867
    private function createAttributeValue(string $attribute, mixed $value, ?string $format = null, array &$context = []): mixed
868
    {
869
        try {
870
            return $this->createAndValidateAttributeValue($attribute, $value, $format, $context);
389✔
871
        } catch (NotNormalizableValueException $exception) {
28✔
872
            if (!isset($context['not_normalizable_value_exceptions'])) {
20✔
873
                throw $exception;
19✔
874
            }
UNCOV
875
            $context['not_normalizable_value_exceptions'][] = $exception;
1✔
876

UNCOV
877
            throw $exception;
1✔
878
        }
879
    }
880

881
    private function createAndValidateAttributeValue(string $attribute, mixed $value, ?string $format = null, array $context = []): mixed
882
    {
883
        $propertyMetadata = $this->propertyMetadataFactory->create($context['resource_class'], $attribute, $this->getFactoryOptions($context));
411✔
884
        $types = $propertyMetadata->getBuiltinTypes() ?? [];
411✔
885
        $isMultipleTypes = \count($types) > 1;
411✔
886

887
        foreach ($types as $type) {
411✔
888
            if (null === $value && ($type->isNullable() || ($context[static::DISABLE_TYPE_ENFORCEMENT] ?? false))) {
403✔
889
                return $value;
5✔
890
            }
891

892
            $collectionValueType = $type->getCollectionValueTypes()[0] ?? null;
402✔
893

894
            /* From @see AbstractObjectNormalizer::validateAndDenormalize() */
895
            // Fix a collection that contains the only one element
896
            // This is special to xml format only
897
            if ('xml' === $format && null !== $collectionValueType && (!\is_array($value) || !\is_int(key($value)))) {
402✔
898
                $value = [$value];
2✔
899
            }
900

901
            if (
902
                $type->isCollection()
402✔
903
                && null !== $collectionValueType
402✔
904
                && null !== ($className = $collectionValueType->getClassName())
402✔
905
                && $this->resourceClassResolver->isResourceClass($className)
402✔
906
            ) {
907
                $resourceClass = $this->resourceClassResolver->getResourceClass(null, $className);
31✔
908
                $context['resource_class'] = $resourceClass;
31✔
909
                unset($context['uri_variables']);
31✔
910

911
                return $this->denormalizeCollection($attribute, $propertyMetadata, $type, $resourceClass, $value, $format, $context);
31✔
912
            }
913

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

921
                return $this->denormalizeRelation($attribute, $propertyMetadata, $resourceClass, $value, $format, $childContext);
103✔
922
            }
923

924
            if (
925
                $type->isCollection()
360✔
926
                && null !== $collectionValueType
360✔
927
                && null !== ($className = $collectionValueType->getClassName())
360✔
928
                && \is_array($value)
360✔
929
            ) {
930
                if (!$this->serializer instanceof DenormalizerInterface) {
6✔
931
                    throw new LogicException(\sprintf('The injected serializer must be an instance of "%s".', DenormalizerInterface::class));
×
932
                }
933

934
                unset($context['resource_class'], $context['uri_variables']);
6✔
935

936
                return $this->serializer->denormalize($value, $className.'[]', $format, $context);
6✔
937
            }
938

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

944
                unset($context['resource_class'], $context['uri_variables']);
34✔
945

946
                return $this->serializer->denormalize($value, $className, $format, $context);
34✔
947
            }
948

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

958
                switch ($type->getBuiltinType()) {
30✔
959
                    case Type::BUILTIN_TYPE_BOOL:
30✔
960
                        // according to http://www.w3.org/TR/xmlschema-2/#boolean, valid representations are "false", "true", "0" and "1"
961
                        if ('false' === $value || '0' === $value) {
8✔
962
                            $value = false;
4✔
963
                        } elseif ('true' === $value || '1' === $value) {
4✔
964
                            $value = true;
4✔
965
                        } else {
966
                            // union/intersect types: try the next type, if not valid, an exception will be thrown at the end
967
                            if ($isMultipleTypes) {
×
968
                                break 2;
×
969
                            }
970
                            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);
×
971
                        }
972
                        break;
8✔
973
                    case Type::BUILTIN_TYPE_INT:
22✔
974
                        if (ctype_digit($value) || ('-' === $value[0] && ctype_digit(substr($value, 1)))) {
8✔
975
                            $value = (int) $value;
8✔
976
                        } else {
977
                            // union/intersect types: try the next type, if not valid, an exception will be thrown at the end
978
                            if ($isMultipleTypes) {
×
979
                                break 2;
×
980
                            }
981
                            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);
×
982
                        }
983
                        break;
8✔
984
                    case Type::BUILTIN_TYPE_FLOAT:
14✔
985
                        if (is_numeric($value)) {
8✔
986
                            return (float) $value;
2✔
987
                        }
988

989
                        switch ($value) {
990
                            case 'NaN':
6✔
991
                                return \NAN;
2✔
992
                            case 'INF':
4✔
993
                                return \INF;
2✔
994
                            case '-INF':
2✔
995
                                return -\INF;
2✔
996
                            default:
997
                                // union/intersect types: try the next type, if not valid, an exception will be thrown at the end
998
                                if ($isMultipleTypes) {
×
999
                                    break 3;
×
1000
                                }
1001
                                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);
×
1002
                        }
1003
                }
1004
            }
1005

1006
            if ($context[static::DISABLE_TYPE_ENFORCEMENT] ?? false) {
338✔
1007
                return $value;
×
1008
            }
1009

1010
            try {
1011
                $this->validateType($attribute, $type, $value, $format, $context);
338✔
1012

1013
                break;
330✔
1014
            } catch (NotNormalizableValueException $e) {
14✔
1015
                // union/intersect types: try the next type
1016
                if (!$isMultipleTypes) {
14✔
1017
                    throw $e;
8✔
1018
                }
1019
            }
1020
        }
1021

1022
        return $value;
338✔
1023
    }
1024

1025
    /**
1026
     * Sets a value of the object using the PropertyAccess component.
1027
     */
1028
    private function setValue(object $object, string $attributeName, mixed $value): void
1029
    {
1030
        try {
1031
            $this->propertyAccessor->setValue($object, $attributeName, $value);
372✔
1032
        } catch (NoSuchPropertyException) {
17✔
1033
            // Properties not found are ignored
1034
        }
1035
    }
1036
}
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