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

api-platform / core / 14837294296

05 May 2025 01:12PM UTC coverage: 8.459% (-0.004%) from 8.463%
14837294296

push

github

web-flow
fix(serializer): throw NotNormalizableValueException when resource not found or invalid IRI on denormalization

0 of 33 new or added lines in 2 files covered. (0.0%)

116 existing lines in 57 files now uncovered.

13400 of 158414 relevant lines covered (8.46%)

22.88 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
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,034✔
68
            $defaultContext['circular_reference_handler'] = fn ($object): ?string => $this->iriConverter->getIriFromResource($object);
2,022✔
69
        }
70

71
        parent::__construct($classMetadataFactory, $nameConverter, null, null, \Closure::fromCallable($this->getObjectClass(...)), $defaultContext);
2,034✔
72
        $this->propertyAccessor = $propertyAccessor ?: PropertyAccess::createPropertyAccessor();
2,034✔
73
        $this->resourceAccessChecker = $resourceAccessChecker;
2,034✔
74
        $this->resourceMetadataCollectionFactory = $resourceMetadataCollectionFactory;
2,034✔
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,787✔
83
            return false;
678✔
84
        }
85

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

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

94
    public function getSupportedTypes(?string $format): array
95
    {
96
        return [
1,846✔
97
            'object' => true,
1,846✔
98
        ];
1,846✔
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,733✔
109
        if ($outputClass = $this->getOutputClass($context)) {
1,733✔
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,733✔
125
            unset($context['operation_name'], $context['operation'], $context['iri']);
16✔
126
        }
127

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

132
        $context['api_normalize'] = true;
1,733✔
133
        $iri = $context['iri'] ??= $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_URL, $context['operation'] ?? null, $context);
1,733✔
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,733✔
146
        unset($context['api_empty_resource_as_iri']);
1,733✔
147

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

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

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

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

160
        if ($emptyResourceAsIri && \is_array($data) && 0 === \count($data)) {
1,733✔
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,733✔
171
            $this->tagCollector->collect($context);
1,514✔
172
        }
173

174
        return $data;
1,733✔
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) {
×
NEW
227
                if (!isset($context['not_normalizable_value_exceptions'])) {
×
NEW
228
                    throw new UnexpectedValueException($e->getMessage(), $e->getCode(), $e);
×
229
                }
230

NEW
231
                throw NotNormalizableValueException::createForUnexpectedDataType(\sprintf('The type of the "%s" resource "string" (IRI), "%s" given.', $resourceClass, \gettype($data)), $data, [$resourceClass], $context['deserialization_path'] ?? null, true, $e->getCode(), $e);
×
232
            } catch (InvalidArgumentException $e) {
×
NEW
233
                if (!isset($context['not_normalizable_value_exceptions'])) {
×
NEW
234
                    throw new UnexpectedValueException(\sprintf('Invalid IRI "%s".', $data), $e->getCode(), $e);
×
235
                }
236

NEW
237
                throw NotNormalizableValueException::createForUnexpectedDataType(\sprintf('The type of the "%s" resource "string" (IRI), "%s" given.', $resourceClass, \gettype($data)), $data, [$resourceClass], $context['deserialization_path'] ?? null, true, $e->getCode(), $e);
×
238
            }
239
        }
240

241
        if (!\is_array($data)) {
457✔
242
            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✔
243
        }
244

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

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

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

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

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

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

278
        return $object;
427✔
279
    }
280

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

294
            return $object;
97✔
295
        }
296

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

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

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

312
                $allowed = false === $allowedAttributes || (\is_array($allowedAttributes) && \in_array($paramName, $allowedAttributes, true));
77✔
313
                $ignored = !$this->isAllowedAttribute($class, $paramName, $format, $context);
77✔
314
                if ($constructorParameter->isVariadic()) {
77✔
315
                    if ($allowed && !$ignored && (isset($data[$key]) || \array_key_exists($key, $data))) {
×
316
                        if (!\is_array($data[$paramName])) {
×
317
                            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));
×
318
                        }
319

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

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

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

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

360
            if ($missingConstructorArguments) {
168✔
361
                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✔
362
            }
363

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

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

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

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

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

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

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

393
        return $mappedClass;
2✔
394
    }
395

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

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

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

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

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

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

440
        return $allowedAttributes;
1,709✔
441
    }
442

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

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

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

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

474
        return true;
1,685✔
475
    }
476

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

493
        return true;
386✔
494
    }
495

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

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

525
        if (!$isValid) {
338✔
526
            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✔
527
        }
528
    }
529

530
    /**
531
     * Denormalizes a collection of objects.
532
     *
533
     * @throws NotNormalizableValueException
534
     */
535
    protected function denormalizeCollection(string $attribute, ApiProperty $propertyMetadata, Type $type, string $className, mixed $value, ?string $format, array $context): array
536
    {
537
        if (!\is_array($value)) {
31✔
538
            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✔
539
        }
540

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

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

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

563
                $values[$index] = $this->denormalizeRelation($attribute, $propertyMetadata, $className, $obj, $format, $currentChildContext);
26✔
564
                continue 2;
26✔
565
            }
566
            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✔
567
        }
568

569
        return $values;
26✔
570
    }
571

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

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

NEW
595
                throw NotNormalizableValueException::createForUnexpectedDataType($e->getMessage(), $value, [$className], $context['deserialization_path'] ?? null, true, $e->getCode(), $e);
×
596
            }
597
        }
598

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

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

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

611
            return $item;
45✔
612
        }
613

614
        if (!\is_array($value)) {
2✔
615
            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✔
616
        }
617

618
        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✔
619
    }
620

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

704
                return $data;
431✔
705
            }
706

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

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

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

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

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

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

734
                if ($this->tagCollector) {
599✔
735
                    $this->tagCollector->collect($context);
558✔
736
                }
737

738
                return $data;
599✔
739
            }
740

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

813
        return $value;
392✔
814
    }
815

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

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

835
            return $normalizedRelatedObject;
419✔
836
        }
837

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

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

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

854
        return $iri;
176✔
855
    }
856

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

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

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

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

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

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

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

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

909
                        continue;
×
910
                    }
911

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

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

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

930
                        continue;
×
931
                    }
932

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

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

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

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

956
                        continue;
×
957
                    }
958

959
                    throw $e;
×
960
                }
961
            }
962

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

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

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

977
                        continue;
2✔
978
                    }
979

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

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

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

1024
                        switch ($value) {
1025
                            case 'NaN':
6✔
1026
                                return \NAN;
2✔
1027
                            case 'INF':
4✔
1028
                                return \INF;
2✔
1029
                            case '-INF':
2✔
1030
                                return -\INF;
2✔
1031
                            default:
1032
                                // union/intersect types: try the next type, if not valid, an exception will be thrown at the end
1033
                                if ($isMultipleTypes) {
×
1034
                                    break 3;
×
1035
                                }
1036
                                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);
×
1037
                        }
1038
                }
1039
            }
1040

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

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

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

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

1061
        return $value;
338✔
1062
    }
1063

1064
    /**
1065
     * Sets a value of the object using the PropertyAccess component.
1066
     */
1067
    private function setValue(object $object, string $attributeName, mixed $value): void
1068
    {
1069
        try {
1070
            $this->propertyAccessor->setValue($object, $attributeName, $value);
372✔
1071
        } catch (NoSuchPropertyException) {
17✔
1072
            // Properties not found are ignored
1073
        }
1074
    }
1075
}
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