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

api-platform / core / 17327553156

29 Aug 2025 03:13PM UTC coverage: 22.588% (-0.03%) from 22.622%
17327553156

push

github

web-flow
fix(laravel): serialization issue with camelCase relation (#7356)

fixes #7344

0 of 76 new or added lines in 9 files covered. (0.0%)

11415 existing lines in 372 files now uncovered.

11181 of 49499 relevant lines covered (22.59%)

23.68 hits per line

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

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

3
/*
4
 * This file is part of the API Platform project.
5
 *
6
 * (c) Kévin Dunglas <dunglas@gmail.com>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11

12
declare(strict_types=1);
13

14
namespace ApiPlatform\Serializer;
15

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

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

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

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

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

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

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

UNCOV
90
        return $this->resourceClassResolver->isResourceClass($class);
476✔
91
    }
92

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

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

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

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

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

UNCOV
127
        if ($this->resourceClassResolver->isResourceClass($resourceClass)) {
488✔
UNCOV
128
            $context = $this->initContext($resourceClass, $context);
476✔
129
        }
130

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

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

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

UNCOV
151
        $context['object'] = $object;
488✔
UNCOV
152
        $context['format'] = $format;
488✔
153

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

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

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

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

166
            return $iri;
×
167
        }
168

UNCOV
169
        if ($this->tagCollector) {
488✔
UNCOV
170
            $this->tagCollector->collect($context);
458✔
171
        }
172

UNCOV
173
        return $data;
488✔
174
    }
175

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

UNCOV
277
        return $object;
14✔
278
    }
279

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

UNCOV
293
            return $object;
2✔
294
        }
295

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

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

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

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

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

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

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

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

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

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

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

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

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

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

383
        if (!isset($data[$mapping->getTypeProperty()])) {
×
384
            throw NotNormalizableValueException::createForUnexpectedDataType(\sprintf('Type property "%s" not found for the abstract object "%s".', $mapping->getTypeProperty(), $class), null, ['string'], isset($context['deserialization_path']) ? $context['deserialization_path'].'.'.$mapping->getTypeProperty() : $mapping->getTypeProperty());
×
385
        }
386

387
        $type = $data[$mapping->getTypeProperty()];
×
388
        if (null === ($mappedClass = $mapping->getClassForType($type))) {
×
389
            throw NotNormalizableValueException::createForUnexpectedDataType(\sprintf('The type "%s" is not a valid value.', $type), $type, ['string'], isset($context['deserialization_path']) ? $context['deserialization_path'].'.'.$mapping->getTypeProperty() : $mapping->getTypeProperty(), true);
×
390
        }
391

392
        return $mappedClass;
×
393
    }
394

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

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

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

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

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

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

UNCOV
439
        return $allowedAttributes;
476✔
440
    }
441

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

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

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

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

UNCOV
473
        return true;
468✔
474
    }
475

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

UNCOV
492
        return true;
12✔
493
    }
494

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

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

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

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

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

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

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

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

568
        return $values;
×
569
    }
570

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

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

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

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

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

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

UNCOV
610
            return $item;
2✔
611
        }
612

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

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

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

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

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

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

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

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

UNCOV
664
        $types = $propertyMetadata->getBuiltinTypes() ?? [];
474✔
665

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

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

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

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

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

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

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

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

UNCOV
703
                return $data;
14✔
704
            }
705

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

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

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

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

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

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

UNCOV
733
                if ($this->tagCollector) {
22✔
UNCOV
734
                    $this->tagCollector->collect($context);
14✔
735
                }
736

UNCOV
737
                return $data;
22✔
738
            }
739

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

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

750
            // Anonymous resources
UNCOV
751
            if ($className) {
472✔
UNCOV
752
                $childContext = $this->createChildContext($this->createOperationContext($context, $className, $propertyMetadata), $attribute, $format);
184✔
UNCOV
753
                $attributeValue = $this->propertyAccessor->getValue($object, $attribute);
184✔
754

UNCOV
755
                return $this->serializer->normalize($attributeValue, $format, $childContext);
184✔
756
            }
757

UNCOV
758
            if ('array' === $type->getBuiltinType()) {
466✔
UNCOV
759
                if ($className = ($type->getCollectionValueTypes()[0] ?? null)?->getClassName()) {
64✔
UNCOV
760
                    $context = $this->createOperationContext($context, $className, $propertyMetadata);
8✔
761
                }
762

UNCOV
763
                $childContext = $this->createChildContext($context, $attribute, $format);
64✔
UNCOV
764
                $attributeValue = $this->propertyAccessor->getValue($object, $attribute);
64✔
765

UNCOV
766
                return $this->serializer->normalize($attributeValue, $format, $childContext);
64✔
767
            }
768
        }
769

UNCOV
770
        if (!$this->serializer instanceof NormalizerInterface) {
468✔
771
            throw new LogicException(\sprintf('The injected serializer must be an instance of "%s".', NormalizerInterface::class));
×
772
        }
773

UNCOV
774
        unset(
468✔
UNCOV
775
            $context['resource_class'],
468✔
UNCOV
776
            $context['force_resource_class'],
468✔
UNCOV
777
            $context['uri_variables']
468✔
UNCOV
778
        );
468✔
779

UNCOV
780
        $attributeValue = $this->propertyAccessor->getValue($object, $attribute);
468✔
781

UNCOV
782
        return $this->serializer->normalize($attributeValue, $format, $context);
466✔
783
    }
784

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

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

UNCOV
805
            $value[$index] = $this->normalizeRelation($propertyMetadata, $obj, $resourceClass, $format, $context);
2✔
806
        }
807

UNCOV
808
        return $value;
14✔
809
    }
810

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

UNCOV
824
            $relatedContext = $this->createOperationContext($context, $resourceClass, $propertyMetadata);
16✔
UNCOV
825
            $normalizedRelatedObject = $this->serializer->normalize($relatedObject, $format, $relatedContext);
16✔
UNCOV
826
            if (!\is_string($normalizedRelatedObject) && !\is_array($normalizedRelatedObject) && !$normalizedRelatedObject instanceof \ArrayObject && null !== $normalizedRelatedObject) {
16✔
827
                throw new UnexpectedValueException('Expected normalized relation to be an IRI, array, \ArrayObject or null');
×
828
            }
829

UNCOV
830
            return $normalizedRelatedObject;
16✔
831
        }
832

UNCOV
833
        $context['iri'] = $iri = $this->iriConverter->getIriFromResource(resource: $relatedObject, context: $context);
8✔
UNCOV
834
        $context['data'] = $iri;
8✔
UNCOV
835
        $context['object'] = $relatedObject;
8✔
UNCOV
836
        unset($context['property_metadata'], $context['api_attribute']);
8✔
837

UNCOV
838
        if ($this->tagCollector) {
8✔
UNCOV
839
            $this->tagCollector->collect($context);
4✔
UNCOV
840
        } elseif (isset($context['resources'])) {
4✔
841
            $context['resources'][$iri] = $iri;
×
842
        }
843

UNCOV
844
        $push = $propertyMetadata->getPush() ?? false;
8✔
UNCOV
845
        if (isset($context['resources_to_push']) && $push) {
8✔
846
            $context['resources_to_push'][$iri] = $iri;
×
847
        }
848

UNCOV
849
        return $iri;
8✔
850
    }
851

852
    private function createAttributeValue(string $attribute, mixed $value, ?string $format = null, array &$context = []): mixed
853
    {
854
        try {
UNCOV
855
            return $this->createAndValidateAttributeValue($attribute, $value, $format, $context);
12✔
UNCOV
856
        } catch (NotNormalizableValueException $exception) {
2✔
857
            if (!isset($context['not_normalizable_value_exceptions'])) {
×
858
                throw $exception;
×
859
            }
860
            $context['not_normalizable_value_exceptions'][] = $exception;
×
861

862
            throw $exception;
×
863
        }
864
    }
865

866
    private function createAndValidateAttributeValue(string $attribute, mixed $value, ?string $format = null, array $context = []): mixed
867
    {
UNCOV
868
        $propertyMetadata = $this->propertyMetadataFactory->create($context['resource_class'], $attribute, $this->getFactoryOptions($context));
14✔
UNCOV
869
        $types = $propertyMetadata->getBuiltinTypes() ?? [];
14✔
UNCOV
870
        $isMultipleTypes = \count($types) > 1;
14✔
UNCOV
871
        $denormalizationException = null;
14✔
872

UNCOV
873
        foreach ($types as $type) {
14✔
UNCOV
874
            if (null === $value && ($type->isNullable() || ($context[static::DISABLE_TYPE_ENFORCEMENT] ?? false))) {
14✔
875
                return $value;
×
876
            }
877

UNCOV
878
            $collectionValueType = $type->getCollectionValueTypes()[0] ?? null;
14✔
879

880
            /* From @see AbstractObjectNormalizer::validateAndDenormalize() */
881
            // Fix a collection that contains the only one element
882
            // This is special to xml format only
UNCOV
883
            if ('xml' === $format && null !== $collectionValueType && (!\is_array($value) || !\is_int(key($value)))) {
14✔
884
                $value = [$value];
×
885
            }
886

887
            if (
UNCOV
888
                $type->isCollection()
14✔
UNCOV
889
                && null !== $collectionValueType
14✔
UNCOV
890
                && null !== ($className = $collectionValueType->getClassName())
14✔
UNCOV
891
                && $this->resourceClassResolver->isResourceClass($className)
14✔
892
            ) {
893
                $resourceClass = $this->resourceClassResolver->getResourceClass(null, $className);
×
894
                $context['resource_class'] = $resourceClass;
×
895
                unset($context['uri_variables']);
×
896

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

904
                        continue;
×
905
                    }
906

907
                    throw $e;
×
908
                }
909
            }
910

911
            if (
UNCOV
912
                null !== ($className = $type->getClassName())
14✔
UNCOV
913
                && $this->resourceClassResolver->isResourceClass($className)
14✔
914
            ) {
UNCOV
915
                $resourceClass = $this->resourceClassResolver->getResourceClass(null, $className);
6✔
UNCOV
916
                $childContext = $this->createChildContext($this->createOperationContext($context, $resourceClass, $propertyMetadata), $attribute, $format);
6✔
917

918
                try {
UNCOV
919
                    return $this->denormalizeRelation($attribute, $propertyMetadata, $resourceClass, $value, $format, $childContext);
6✔
UNCOV
920
                } catch (NotNormalizableValueException $e) {
2✔
921
                    // union/intersect types: try the next type, if not valid, an exception will be thrown at the end
922
                    if ($isMultipleTypes) {
×
923
                        $denormalizationException ??= $e;
×
924

925
                        continue;
×
926
                    }
927

928
                    throw $e;
×
929
                }
930
            }
931

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

942
                unset($context['resource_class'], $context['uri_variables']);
×
943

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

951
                        continue;
×
952
                    }
953

954
                    throw $e;
×
955
                }
956
            }
957

UNCOV
958
            if (null !== $className = $type->getClassName()) {
10✔
959
                if (!$this->serializer instanceof DenormalizerInterface) {
2✔
960
                    throw new LogicException(\sprintf('The injected serializer must be an instance of "%s".', DenormalizerInterface::class));
×
961
                }
962

963
                unset($context['resource_class'], $context['uri_variables']);
2✔
964

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

972
                        continue;
×
973
                    }
974

975
                    throw $e;
×
976
                }
977
            }
978

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

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

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

UNCOV
1036
            if ($context[static::DISABLE_TYPE_ENFORCEMENT] ?? false) {
10✔
1037
                return $value;
×
1038
            }
1039

1040
            try {
UNCOV
1041
                $this->validateType($attribute, $type, $value, $format, $context);
10✔
1042

UNCOV
1043
                break;
10✔
1044
            } catch (NotNormalizableValueException $e) {
×
1045
                // union/intersect types: try the next type
1046
                if (!$isMultipleTypes) {
×
1047
                    throw $e;
×
1048
                }
1049
            }
1050
        }
1051

UNCOV
1052
        if ($denormalizationException) {
10✔
1053
            throw $denormalizationException;
×
1054
        }
1055

UNCOV
1056
        return $value;
10✔
1057
    }
1058

1059
    /**
1060
     * Sets a value of the object using the PropertyAccess component.
1061
     */
1062
    private function setValue(object $object, string $attributeName, mixed $value): void
1063
    {
1064
        try {
UNCOV
1065
            $this->propertyAccessor->setValue($object, $attributeName, $value);
10✔
1066
        } catch (NoSuchPropertyException) {
2✔
1067
            // Properties not found are ignored
1068
        }
1069
    }
1070
}
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