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

api-platform / core / 15776845112

20 Jun 2025 10:24AM UTC coverage: 22.065%. Remained the same
15776845112

Pull #7237

github

web-flow
Merge dcdc2d081 into 42f0ce79f
Pull Request #7237: ci: bump lowest dependencies

0 of 1 new or added line in 1 file covered. (0.0%)

62 existing lines in 1 file now uncovered.

11487 of 52060 relevant lines covered (22.06%)

21.72 hits per line

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

56.48
/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\PropertyInfoExtractor;
33
use Symfony\Component\PropertyInfo\Type as LegacyType;
34
use Symfony\Component\Serializer\Encoder\CsvEncoder;
35
use Symfony\Component\Serializer\Encoder\XmlEncoder;
36
use Symfony\Component\Serializer\Exception\LogicException;
37
use Symfony\Component\Serializer\Exception\MissingConstructorArgumentsException;
38
use Symfony\Component\Serializer\Exception\NotNormalizableValueException;
39
use Symfony\Component\Serializer\Exception\RuntimeException;
40
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
41
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
42
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
43
use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer;
44
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
45
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
46
use Symfony\Component\TypeInfo\Type;
47
use Symfony\Component\TypeInfo\Type\BuiltinType;
48
use Symfony\Component\TypeInfo\Type\CollectionType;
49
use Symfony\Component\TypeInfo\Type\CompositeTypeInterface;
50
use Symfony\Component\TypeInfo\Type\NullableType;
51
use Symfony\Component\TypeInfo\Type\ObjectType;
52
use Symfony\Component\TypeInfo\Type\WrappingTypeInterface;
53
use Symfony\Component\TypeInfo\TypeIdentifier;
54

55
/**
56
 * Base item normalizer.
57
 *
58
 * @author Kévin Dunglas <dunglas@gmail.com>
59
 */
60
abstract class AbstractItemNormalizer extends AbstractObjectNormalizer
61
{
62
    use ClassInfoTrait;
63
    use CloneTrait;
64
    use ContextTrait;
65
    use InputOutputMetadataTrait;
66
    use OperationContextTrait;
67

68
    protected PropertyAccessorInterface $propertyAccessor;
69
    protected array $localCache = [];
70
    protected array $localFactoryOptionsCache = [];
71
    protected ?ResourceAccessCheckerInterface $resourceAccessChecker;
72

73
    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)
74
    {
75
        if (!isset($defaultContext['circular_reference_handler'])) {
526✔
76
            $defaultContext['circular_reference_handler'] = fn ($object): ?string => $this->iriConverter->getIriFromResource($object);
514✔
77
        }
78

79
        parent::__construct($classMetadataFactory, $nameConverter, null, null, \Closure::fromCallable($this->getObjectClass(...)), $defaultContext);
526✔
80
        $this->propertyAccessor = $propertyAccessor ?: PropertyAccess::createPropertyAccessor();
526✔
81
        $this->resourceAccessChecker = $resourceAccessChecker;
526✔
82
        $this->resourceMetadataCollectionFactory = $resourceMetadataCollectionFactory;
526✔
83
    }
84

85
    /**
86
     * {@inheritdoc}
87
     */
88
    public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
89
    {
90
        if (!\is_object($data) || is_iterable($data)) {
452✔
91
            return false;
222✔
92
        }
93

94
        $class = $context['force_resource_class'] ?? $this->getObjectClass($data);
440✔
95
        if (($context['output']['class'] ?? null) === $class) {
440✔
96
            return true;
12✔
97
        }
98

99
        return $this->resourceClassResolver->isResourceClass($class);
436✔
100
    }
101

102
    public function getSupportedTypes(?string $format): array
103
    {
104
        return [
462✔
105
            'object' => true,
462✔
106
        ];
462✔
107
    }
108

109
    /**
110
     * {@inheritdoc}
111
     *
112
     * @throws LogicException
113
     */
114
    public function normalize(mixed $object, ?string $format = null, array $context = []): array|string|int|float|bool|\ArrayObject|null
115
    {
116
        $resourceClass = $context['force_resource_class'] ?? $this->getObjectClass($object);
448✔
117
        if ($outputClass = $this->getOutputClass($context)) {
448✔
118
            if (!$this->serializer instanceof NormalizerInterface) {
12✔
119
                throw new LogicException('Cannot normalize the output because the injected serializer is not a normalizer');
×
120
            }
121

122
            unset($context['output'], $context['operation'], $context['operation_name']);
12✔
123
            $context['resource_class'] = $outputClass;
12✔
124
            $context['api_sub_level'] = true;
12✔
125
            $context[self::ALLOW_EXTRA_ATTRIBUTES] = false;
12✔
126

127
            return $this->serializer->normalize($object, $format, $context);
12✔
128
        }
129

130
        // Never remove this, with `application/json` we don't use our AbstractCollectionNormalizer and we need
131
        // to remove the collection operation from our context or we'll introduce security issues
132
        if (isset($context['operation']) && $context['operation'] instanceof CollectionOperationInterface) {
448✔
133
            unset($context['operation_name'], $context['operation'], $context['iri']);
4✔
134
        }
135

136
        if ($this->resourceClassResolver->isResourceClass($resourceClass)) {
448✔
137
            $context = $this->initContext($resourceClass, $context);
436✔
138
        }
139

140
        $context['api_normalize'] = true;
448✔
141
        $iri = $context['iri'] ??= $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_URL, $context['operation'] ?? null, $context);
448✔
142

143
        /*
144
         * When true, converts the normalized data array of a resource into an
145
         * IRI, if the normalized data array is empty.
146
         *
147
         * This is useful when traversing from a non-resource towards an attribute
148
         * which is a resource, as we do not have the benefit of {@see ApiProperty::isReadableLink}.
149
         *
150
         * It must not be propagated to resources, as {@see ApiProperty::isReadableLink}
151
         * should take effect.
152
         */
153
        $emptyResourceAsIri = $context['api_empty_resource_as_iri'] ?? false;
448✔
154
        unset($context['api_empty_resource_as_iri']);
448✔
155

156
        if (!$this->tagCollector && isset($context['resources'])) {
448✔
157
            $context['resources'][$iri] = $iri;
×
158
        }
159

160
        $context['object'] = $object;
448✔
161
        $context['format'] = $format;
448✔
162

163
        $data = parent::normalize($object, $format, $context);
448✔
164

165
        $context['data'] = $data;
448✔
166
        unset($context['property_metadata'], $context['api_attribute']);
448✔
167

168
        if ($emptyResourceAsIri && \is_array($data) && 0 === \count($data)) {
448✔
169
            $context['data'] = $iri;
×
170

171
            if ($this->tagCollector) {
×
172
                $this->tagCollector->collect($context);
×
173
            }
174

175
            return $iri;
×
176
        }
177

178
        if ($this->tagCollector) {
448✔
179
            $this->tagCollector->collect($context);
418✔
180
        }
181

182
        return $data;
448✔
183
    }
184

185
    /**
186
     * {@inheritdoc}
187
     */
188
    public function supportsDenormalization(mixed $data, string $type, ?string $format = null, array $context = []): bool
189
    {
190
        if (($context['input']['class'] ?? null) === $type) {
16✔
191
            return true;
×
192
        }
193

194
        return $this->localCache[$type] ?? $this->localCache[$type] = $this->resourceClassResolver->isResourceClass($type);
16✔
195
    }
196

197
    /**
198
     * {@inheritdoc}
199
     */
200
    public function denormalize(mixed $data, string $class, ?string $format = null, array $context = []): mixed
201
    {
202
        $resourceClass = $class;
16✔
203

204
        if ($inputClass = $this->getInputClass($context)) {
16✔
205
            if (!$this->serializer instanceof DenormalizerInterface) {
2✔
206
                throw new LogicException('Cannot denormalize the input because the injected serializer is not a denormalizer');
×
207
            }
208

209
            unset($context['input'], $context['operation'], $context['operation_name'], $context['uri_variables']);
2✔
210
            $context['resource_class'] = $inputClass;
2✔
211

212
            try {
213
                return $this->serializer->denormalize($data, $inputClass, $format, $context);
2✔
214
            } catch (NotNormalizableValueException $e) {
×
215
                throw new UnexpectedValueException('The input data is misformatted.', $e->getCode(), $e);
×
216
            }
217
        }
218

219
        if (null === $objectToPopulate = $this->extractObjectToPopulate($resourceClass, $context, static::OBJECT_TO_POPULATE)) {
16✔
220
            $normalizedData = \is_scalar($data) ? [$data] : $this->prepareForDenormalization($data);
16✔
221
            $class = $this->getClassDiscriminatorResolvedClass($normalizedData, $class, $context);
16✔
222
        }
223

224
        $context['api_denormalize'] = true;
16✔
225

226
        if ($this->resourceClassResolver->isResourceClass($class)) {
16✔
227
            $resourceClass = $this->resourceClassResolver->getResourceClass($objectToPopulate, $class);
16✔
228
            $context['resource_class'] = $resourceClass;
16✔
229
        }
230

231
        if (\is_string($data)) {
16✔
232
            try {
233
                return $this->iriConverter->getResourceFromIri($data, $context + ['fetch_data' => true]);
2✔
234
            } catch (ItemNotFoundException $e) {
×
235
                if (!isset($context['not_normalizable_value_exceptions'])) {
×
236
                    throw new UnexpectedValueException($e->getMessage(), $e->getCode(), $e);
×
237
                }
238

239
                throw NotNormalizableValueException::createForUnexpectedDataType($e->getMessage(), $data, [$resourceClass], $context['deserialization_path'] ?? null, true, $e->getCode(), $e);
×
240
            } catch (InvalidArgumentException $e) {
×
241
                if (!isset($context['not_normalizable_value_exceptions'])) {
×
242
                    throw new UnexpectedValueException(\sprintf('Invalid IRI "%s".', $data), $e->getCode(), $e);
×
243
                }
244

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

249
        if (!\is_array($data)) {
14✔
250
            throw NotNormalizableValueException::createForUnexpectedDataType(\sprintf('The type of the "%s" resource must be "array" (nested document) or "string" (IRI), "%s" given.', $resourceClass, \gettype($data)), $data, ['array', 'string'], $context['deserialization_path'] ?? null);
×
251
        }
252

253
        $previousObject = $this->clone($objectToPopulate);
14✔
254
        $object = parent::denormalize($data, $class, $format, $context);
14✔
255

256
        if (!$this->resourceClassResolver->isResourceClass($class)) {
12✔
257
            return $object;
×
258
        }
259

260
        // Bypass the post-denormalize attribute revert logic if the object could not be
261
        // cloned since we cannot possibly revert any changes made to it.
262
        if (null !== $objectToPopulate && null === $previousObject) {
12✔
263
            return $object;
×
264
        }
265

266
        $options = $this->getFactoryOptions($context);
12✔
267
        $propertyNames = iterator_to_array($this->propertyNameCollectionFactory->create($resourceClass, $options));
12✔
268

269
        // Revert attributes that aren't allowed to be changed after a post-denormalize check
270
        foreach (array_keys($data) as $attribute) {
12✔
271
            $attribute = $this->nameConverter ? $this->nameConverter->denormalize((string) $attribute) : $attribute;
10✔
272
            if (!\in_array($attribute, $propertyNames, true)) {
10✔
273
                continue;
×
274
            }
275

276
            if (!$this->canAccessAttributePostDenormalize($object, $previousObject, $attribute, $context)) {
10✔
277
                if (null !== $previousObject) {
×
278
                    $this->setValue($object, $attribute, $this->propertyAccessor->getValue($previousObject, $attribute));
×
279
                } else {
280
                    $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $attribute, $options);
×
281
                    $this->setValue($object, $attribute, $propertyMetadata->getDefault());
×
282
                }
283
            }
284
        }
285

286
        return $object;
12✔
287
    }
288

289
    /**
290
     * Method copy-pasted from symfony/serializer.
291
     * Remove it after symfony/serializer version update @see https://github.com/symfony/symfony/pull/28263.
292
     *
293
     * {@inheritdoc}
294
     *
295
     * @internal
296
     */
297
    protected function instantiateObject(array &$data, string $class, array &$context, \ReflectionClass $reflectionClass, array|bool $allowedAttributes, ?string $format = null): object
298
    {
299
        if (null !== $object = $this->extractObjectToPopulate($class, $context, static::OBJECT_TO_POPULATE)) {
14✔
300
            unset($context[static::OBJECT_TO_POPULATE]);
×
301

302
            return $object;
×
303
        }
304

305
        $class = $this->getClassDiscriminatorResolvedClass($data, $class, $context);
14✔
306
        $reflectionClass = new \ReflectionClass($class);
14✔
307

308
        $constructor = $this->getConstructor($data, $class, $context, $reflectionClass, $allowedAttributes);
14✔
309
        if ($constructor) {
14✔
310
            $constructorParameters = $constructor->getParameters();
12✔
311

312
            $params = [];
12✔
313
            $missingConstructorArguments = [];
12✔
314
            foreach ($constructorParameters as $constructorParameter) {
12✔
315
                $paramName = $constructorParameter->name;
8✔
316
                $key = $this->nameConverter ? $this->nameConverter->normalize($paramName, $class, $format, $context) : $paramName;
8✔
317
                $attributeContext = $this->getAttributeDenormalizationContext($class, $paramName, $context);
8✔
318
                $attributeContext['deserialization_path'] = $attributeContext['deserialization_path'] ?? $key;
8✔
319

320
                $allowed = false === $allowedAttributes || (\is_array($allowedAttributes) && \in_array($paramName, $allowedAttributes, true));
8✔
321
                $ignored = !$this->isAllowedAttribute($class, $paramName, $format, $context);
8✔
322
                if ($constructorParameter->isVariadic()) {
8✔
323
                    if ($allowed && !$ignored && (isset($data[$key]) || \array_key_exists($key, $data))) {
×
324
                        if (!\is_array($data[$paramName])) {
×
325
                            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));
×
326
                        }
327

328
                        $params[] = $data[$paramName];
×
329
                    }
330
                } elseif ($allowed && !$ignored && (isset($data[$key]) || \array_key_exists($key, $data))) {
8✔
331
                    try {
332
                        $params[] = $this->createConstructorArgument($data[$key], $key, $constructorParameter, $attributeContext, $format);
2✔
333
                    } catch (NotNormalizableValueException $exception) {
2✔
334
                        if (!isset($context['not_normalizable_value_exceptions'])) {
2✔
335
                            throw $exception;
×
336
                        }
337
                        $context['not_normalizable_value_exceptions'][] = $exception;
2✔
338
                    }
339

340
                    // Don't run set for a parameter passed to the constructor
341
                    unset($data[$key]);
2✔
342
                } elseif (isset($context[static::DEFAULT_CONSTRUCTOR_ARGUMENTS][$class][$key])) {
8✔
343
                    $params[] = $context[static::DEFAULT_CONSTRUCTOR_ARGUMENTS][$class][$key];
×
344
                } elseif ($constructorParameter->isDefaultValueAvailable()) {
8✔
345
                    $params[] = $constructorParameter->getDefaultValue();
6✔
346
                } else {
347
                    if (!isset($context['not_normalizable_value_exceptions'])) {
2✔
348
                        $missingConstructorArguments[] = $constructorParameter->name;
×
349
                    }
350

351
                    $constructorParameterType = 'unknown';
2✔
352
                    $reflectionType = $constructorParameter->getType();
2✔
353
                    if ($reflectionType instanceof \ReflectionNamedType) {
2✔
354
                        $constructorParameterType = $reflectionType->getName();
2✔
355
                    }
356

357
                    $exception = NotNormalizableValueException::createForUnexpectedDataType(
2✔
358
                        \sprintf('Failed to create object because the class misses the "%s" property.', $constructorParameter->name),
2✔
359
                        null,
2✔
360
                        [$constructorParameterType],
2✔
361
                        $attributeContext['deserialization_path'],
2✔
362
                        true
2✔
363
                    );
2✔
364
                    $context['not_normalizable_value_exceptions'][] = $exception;
2✔
365
                }
366
            }
367

368
            if ($missingConstructorArguments) {
12✔
369
                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);
×
370
            }
371

372
            if (\count($context['not_normalizable_value_exceptions'] ?? []) > 0) {
12✔
373
                return $reflectionClass->newInstanceWithoutConstructor();
2✔
374
            }
375

376
            if ($constructor->isConstructor()) {
10✔
377
                return $reflectionClass->newInstanceArgs($params);
10✔
378
            }
379

380
            return $constructor->invokeArgs(null, $params);
×
381
        }
382

383
        return new $class();
2✔
384
    }
385

386
    protected function getClassDiscriminatorResolvedClass(array $data, string $class, array $context = []): string
387
    {
388
        if (null === $this->classDiscriminatorResolver || (null === $mapping = $this->classDiscriminatorResolver->getMappingForClass($class))) {
16✔
389
            return $class;
16✔
390
        }
391

392
        if (!isset($data[$mapping->getTypeProperty()])) {
×
393
            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());
×
394
        }
395

396
        $type = $data[$mapping->getTypeProperty()];
×
397
        if (null === ($mappedClass = $mapping->getClassForType($type))) {
×
398
            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);
×
399
        }
400

401
        return $mappedClass;
×
402
    }
403

404
    protected function createConstructorArgument($parameterData, string $key, \ReflectionParameter $constructorParameter, array $context, ?string $format = null): mixed
405
    {
406
        return $this->createAndValidateAttributeValue($constructorParameter->name, $parameterData, $format, $context);
2✔
407
    }
408

409
    /**
410
     * {@inheritdoc}
411
     *
412
     * Unused in this context.
413
     *
414
     * @return string[]
415
     */
416
    protected function extractAttributes($object, $format = null, array $context = []): array
417
    {
418
        return [];
×
419
    }
420

421
    /**
422
     * {@inheritdoc}
423
     */
424
    protected function getAllowedAttributes(string|object $classOrObject, array $context, bool $attributesAsString = false): array|bool
425
    {
426
        if (!$this->resourceClassResolver->isResourceClass($context['resource_class'])) {
448✔
427
            return parent::getAllowedAttributes($classOrObject, $context, $attributesAsString);
12✔
428
        }
429

430
        $resourceClass = $this->resourceClassResolver->getResourceClass(null, $context['resource_class']); // fix for abstract classes and interfaces
436✔
431
        $options = $this->getFactoryOptions($context);
436✔
432
        $propertyNames = $this->propertyNameCollectionFactory->create($resourceClass, $options);
436✔
433

434
        $allowedAttributes = [];
436✔
435
        foreach ($propertyNames as $propertyName) {
436✔
436
            $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $propertyName, $options);
428✔
437

438
            if (
439
                $this->isAllowedAttribute($classOrObject, $propertyName, null, $context)
428✔
440
                && (isset($context['api_normalize']) && $propertyMetadata->isReadable()
428✔
441
                    || isset($context['api_denormalize']) && ($propertyMetadata->isWritable() || !\is_object($classOrObject) && $propertyMetadata->isInitializable())
428✔
442
                )
443
            ) {
444
                $allowedAttributes[] = $propertyName;
422✔
445
            }
446
        }
447

448
        return $allowedAttributes;
436✔
449
    }
450

451
    /**
452
     * {@inheritdoc}
453
     */
454
    protected function isAllowedAttribute(object|string $classOrObject, string $attribute, ?string $format = null, array $context = []): bool
455
    {
456
        if (!parent::isAllowedAttribute($classOrObject, $attribute, $format, $context)) {
440✔
457
            return false;
16✔
458
        }
459

460
        return $this->canAccessAttribute(\is_object($classOrObject) ? $classOrObject : null, $attribute, $context);
440✔
461
    }
462

463
    /**
464
     * Check if access to the attribute is granted.
465
     */
466
    protected function canAccessAttribute(?object $object, string $attribute, array $context = []): bool
467
    {
468
        if (!$this->resourceClassResolver->isResourceClass($context['resource_class'])) {
440✔
469
            return true;
12✔
470
        }
471

472
        $options = $this->getFactoryOptions($context);
428✔
473
        $propertyMetadata = $this->propertyMetadataFactory->create($context['resource_class'], $attribute, $options);
428✔
474
        $security = $propertyMetadata->getSecurity() ?? $propertyMetadata->getPolicy();
428✔
475
        if (null !== $this->resourceAccessChecker && $security) {
428✔
476
            return $this->resourceAccessChecker->isGranted($context['resource_class'], $security, [
2✔
477
                'object' => $object,
2✔
478
                'property' => $attribute,
2✔
479
            ]);
2✔
480
        }
481

482
        return true;
428✔
483
    }
484

485
    /**
486
     * Check if access to the attribute is granted.
487
     */
488
    protected function canAccessAttributePostDenormalize(?object $object, ?object $previousObject, string $attribute, array $context = []): bool
489
    {
490
        $options = $this->getFactoryOptions($context);
10✔
491
        $propertyMetadata = $this->propertyMetadataFactory->create($context['resource_class'], $attribute, $options);
10✔
492
        $security = $propertyMetadata->getSecurityPostDenormalize();
10✔
493
        if ($this->resourceAccessChecker && $security) {
10✔
494
            return $this->resourceAccessChecker->isGranted($context['resource_class'], $security, [
×
495
                'object' => $object,
×
496
                'previous_object' => $previousObject,
×
497
                'property' => $attribute,
×
498
            ]);
×
499
        }
500

501
        return true;
10✔
502
    }
503

504
    /**
505
     * {@inheritdoc}
506
     */
507
    protected function setAttributeValue(object $object, string $attribute, mixed $value, ?string $format = null, array $context = []): void
508
    {
509
        try {
510
            $this->setValue($object, $attribute, $this->createAttributeValue($attribute, $value, $format, $context));
12✔
511
        } catch (NotNormalizableValueException $exception) {
4✔
512
            // Only throw if collecting denormalization errors is disabled.
513
            if (!isset($context['not_normalizable_value_exceptions'])) {
2✔
514
                throw $exception;
×
515
            }
516
        }
517
    }
518

519
    /**
520
     * @deprecated since 4.1, use "validateAttributeType" instead
521
     *
522
     * Validates the type of the value. Allows using integers as floats for JSON formats.
523
     *
524
     * @throws NotNormalizableValueException
525
     */
526
    protected function validateType(string $attribute, LegacyType $type, mixed $value, ?string $format = null, array $context = []): void
527
    {
528
        trigger_deprecation('api-platform/serializer', '4.1', 'The "%s()" method is deprecated, use "%s::validateAttributeType()" instead.', __METHOD__, self::class);
×
529

530
        $builtinType = $type->getBuiltinType();
×
531
        if (LegacyType::BUILTIN_TYPE_FLOAT === $builtinType && null !== $format && str_contains($format, 'json')) {
×
532
            $isValid = \is_float($value) || \is_int($value);
×
533
        } else {
534
            $isValid = \call_user_func('is_'.$builtinType, $value);
×
535
        }
536

537
        if (!$isValid) {
×
538
            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);
×
539
        }
540
    }
541

542
    /**
543
     * Validates the type of the value. Allows using integers as floats for JSON formats.
544
     *
545
     * @throws NotNormalizableValueException
546
     */
547
    protected function validateAttributeType(string $attribute, Type $type, mixed $value, ?string $format = null, array $context = []): void
548
    {
549
        if ($type->isIdentifiedBy(TypeIdentifier::FLOAT) && null !== $format && str_contains($format, 'json')) {
8✔
550
            $isValid = \is_float($value) || \is_int($value);
×
551
        } else {
552
            $isValid = $type->accepts($value);
8✔
553
        }
554

555
        if (!$isValid) {
8✔
556
            throw NotNormalizableValueException::createForUnexpectedDataType(\sprintf('The type of the "%s" attribute must be "%s", "%s" given.', $attribute, $type, \gettype($value)), $value, [(string) $type], $context['deserialization_path'] ?? null);
2✔
557
        }
558
    }
559

560
    /**
561
     * @deprecated since 4.1, use "denormalizeObjectCollection" instead.
562
     *
563
     * Denormalizes a collection of objects.
564
     *
565
     * @throws NotNormalizableValueException
566
     */
567
    protected function denormalizeCollection(string $attribute, ApiProperty $propertyMetadata, LegacyType $type, string $className, mixed $value, ?string $format, array $context): array
568
    {
569
        trigger_deprecation('api-platform/serializer', '4.1', 'The "%s()" method is deprecated, use "%s::denormalizeObjectCollection()" instead.', __METHOD__, self::class);
×
570

571
        if (!\is_array($value)) {
×
572
            throw NotNormalizableValueException::createForUnexpectedDataType(\sprintf('The type of the "%s" attribute must be "array", "%s" given.', $attribute, \gettype($value)), $value, ['array'], $context['deserialization_path'] ?? null);
×
573
        }
574

575
        $values = [];
×
576
        $childContext = $this->createChildContext($this->createOperationContext($context, $className), $attribute, $format);
×
577
        $collectionKeyTypes = $type->getCollectionKeyTypes();
×
578
        foreach ($value as $index => $obj) {
×
579
            $currentChildContext = $childContext;
×
580
            if (isset($childContext['deserialization_path'])) {
×
581
                $currentChildContext['deserialization_path'] = "{$childContext['deserialization_path']}[{$index}]";
×
582
            }
583

584
            // no typehint provided on collection key
585
            if (!$collectionKeyTypes) {
×
586
                $values[$index] = $this->denormalizeRelation($attribute, $propertyMetadata, $className, $obj, $format, $currentChildContext);
×
587
                continue;
×
588
            }
589

590
            // validate collection key typehint
591
            foreach ($collectionKeyTypes as $collectionKeyType) {
×
592
                $collectionKeyBuiltinType = $collectionKeyType->getBuiltinType();
×
593
                if (!\call_user_func('is_'.$collectionKeyBuiltinType, $index)) {
×
594
                    continue;
×
595
                }
596

597
                $values[$index] = $this->denormalizeRelation($attribute, $propertyMetadata, $className, $obj, $format, $currentChildContext);
×
598
                continue 2;
×
599
            }
600
            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);
×
601
        }
602

603
        return $values;
×
604
    }
605

606
    /**
607
     * Denormalizes a collection of objects.
608
     *
609
     * @throws NotNormalizableValueException
610
     */
611
    protected function denormalizeObjectCollection(string $attribute, ApiProperty $propertyMetadata, Type $type, string $className, mixed $value, ?string $format, array $context): array
612
    {
613
        if (!\is_array($value)) {
2✔
614
            throw NotNormalizableValueException::createForUnexpectedDataType(\sprintf('The type of the "%s" attribute must be "array", "%s" given.', $attribute, \gettype($value)), $value, ['array'], $context['deserialization_path'] ?? null);
2✔
615
        }
616

617
        $values = [];
×
618
        $childContext = $this->createChildContext($this->createOperationContext($context, $className), $attribute, $format);
×
619

620
        foreach ($value as $index => $obj) {
×
621
            $currentChildContext = $childContext;
×
622
            if (isset($childContext['deserialization_path'])) {
×
623
                $currentChildContext['deserialization_path'] = "{$childContext['deserialization_path']}[{$index}]";
×
624
            }
625

626
            if ($type instanceof CollectionType) {
×
627
                $collectionKeyType = $type->getCollectionKeyType();
×
628

629
                while ($collectionKeyType instanceof WrappingTypeInterface) {
×
630
                    $collectionKeyType = $type->getWrappedType();
×
631
                }
632

633
                if (!$collectionKeyType->accepts($index)) {
×
634
                    throw NotNormalizableValueException::createForUnexpectedDataType(\sprintf('The type of the key "%s" must be "%s", "%s" given.', $index, $type->getCollectionKeyType(), \gettype($index)), $index, [(string) $collectionKeyType], ($context['deserialization_path'] ?? false) ? \sprintf('key(%s)', $context['deserialization_path']) : null, true);
×
635
                }
636
            }
637

638
            $values[$index] = $this->denormalizeRelation($attribute, $propertyMetadata, $className, $obj, $format, $currentChildContext);
×
639
        }
640

641
        return $values;
×
642
    }
643

644
    /**
645
     * Denormalizes a relation.
646
     *
647
     * @throws LogicException
648
     * @throws UnexpectedValueException
649
     * @throws NotNormalizableValueException
650
     */
651
    protected function denormalizeRelation(string $attributeName, ApiProperty $propertyMetadata, string $className, mixed $value, ?string $format, array $context): ?object
652
    {
653
        if (\is_string($value)) {
6✔
654
            try {
655
                return $this->iriConverter->getResourceFromIri($value, $context + ['fetch_data' => true]);
4✔
656
            } catch (ItemNotFoundException $e) {
2✔
657
                if (!isset($context['not_normalizable_value_exceptions'])) {
×
658
                    throw new UnexpectedValueException($e->getMessage(), $e->getCode(), $e);
×
659
                }
660

661
                throw NotNormalizableValueException::createForUnexpectedDataType($e->getMessage(), $value, [$className], $context['deserialization_path'] ?? null, true, $e->getCode(), $e);
×
662
            } catch (InvalidArgumentException $e) {
2✔
663
                if (!isset($context['not_normalizable_value_exceptions'])) {
×
664
                    throw new UnexpectedValueException(\sprintf('Invalid IRI "%s".', $value), $e->getCode(), $e);
×
665
                }
666

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

671
        if ($propertyMetadata->isWritableLink()) {
2✔
672
            $context['api_allow_update'] = true;
×
673

674
            if (!$this->serializer instanceof DenormalizerInterface) {
×
675
                throw new LogicException(\sprintf('The injected serializer must be an instance of "%s".', DenormalizerInterface::class));
×
676
            }
677

678
            $item = $this->serializer->denormalize($value, $className, $format, $context);
×
679
            if (!\is_object($item) && null !== $item) {
×
680
                throw new \UnexpectedValueException('Expected item to be an object or null.');
×
681
            }
682

683
            return $item;
×
684
        }
685

686
        if (!\is_array($value)) {
2✔
687
            throw NotNormalizableValueException::createForUnexpectedDataType(\sprintf('The type of the "%s" attribute must be "array" (nested document) or "string" (IRI), "%s" given.', $attributeName, \gettype($value)), $value, ['array', 'string'], $context['deserialization_path'] ?? null, true);
2✔
688
        }
689

690
        throw NotNormalizableValueException::createForUnexpectedDataType(\sprintf('Nested documents for attribute "%s" are not allowed. Use IRIs instead.', $attributeName), $value, ['array', 'string'], $context['deserialization_path'] ?? null, true);
×
691
    }
692

693
    /**
694
     * Gets the options for the property name collection / property metadata factories.
695
     */
696
    protected function getFactoryOptions(array $context): array
697
    {
698
        $options = [];
448✔
699
        if (isset($context[self::GROUPS])) {
448✔
700
            /* @see https://github.com/symfony/symfony/blob/v4.2.6/src/Symfony/Component/PropertyInfo/Extractor/SerializerExtractor.php */
701
            $options['serializer_groups'] = (array) $context[self::GROUPS];
158✔
702
        }
703

704
        $operationCacheKey = ($context['resource_class'] ?? '').($context['operation_name'] ?? '').($context['root_operation_name'] ?? '');
448✔
705
        $suffix = ($context['api_normalize'] ?? '') ? 'n' : '';
448✔
706
        if ($operationCacheKey && isset($this->localFactoryOptionsCache[$operationCacheKey.$suffix])) {
448✔
707
            return $options + $this->localFactoryOptionsCache[$operationCacheKey.$suffix];
436✔
708
        }
709

710
        // This is a hot spot
711
        if (isset($context['resource_class'])) {
448✔
712
            // Note that the groups need to be read on the root operation
713
            if ($operation = ($context['root_operation'] ?? null)) {
448✔
714
                $options['normalization_groups'] = $operation->getNormalizationContext()['groups'] ?? null;
242✔
715
                $options['denormalization_groups'] = $operation->getDenormalizationContext()['groups'] ?? null;
242✔
716
                $options['operation_name'] = $operation->getName();
242✔
717
            }
718
        }
719

720
        return $options + $this->localFactoryOptionsCache[$operationCacheKey.$suffix] = $options;
448✔
721
    }
722

723
    /**
724
     * {@inheritdoc}
725
     *
726
     * @throws UnexpectedValueException
727
     */
728
    protected function getAttributeValue(object $object, string $attribute, ?string $format = null, array $context = []): mixed
729
    {
730
        $context['api_attribute'] = $attribute;
434✔
731
        $context['property_metadata'] = $propertyMetadata = $this->propertyMetadataFactory->create($context['resource_class'], $attribute, $this->getFactoryOptions($context));
434✔
732

733
        if ($context['api_denormalize'] ?? false) {
434✔
734
            return $this->propertyAccessor->getValue($object, $attribute);
×
735
        }
736

737
        if (!method_exists(PropertyInfoExtractor::class, 'getType')) {
434✔
738
            $types = $propertyMetadata->getBuiltinTypes() ?? [];
×
739

740
            foreach ($types as $type) {
×
741
                if (
742
                    $type->isCollection()
×
743
                    && ($collectionValueType = $type->getCollectionValueTypes()[0] ?? null)
×
744
                    && ($className = $collectionValueType->getClassName())
×
745
                    && $this->resourceClassResolver->isResourceClass($className)
×
746
                ) {
747
                    $childContext = $this->createChildContext($this->createOperationContext($context, $className), $attribute, $format);
×
748

749
                    // @see ApiPlatform\Hal\Serializer\ItemNormalizer:getComponents logic for intentional duplicate content
750
                    // @see ApiPlatform\JsonApi\Serializer\ItemNormalizer:getComponents logic for intentional duplicate content
751
                    if ('jsonld' === $format && $itemUriTemplate = $propertyMetadata->getUriTemplate()) {
×
752
                        $operation = $this->resourceMetadataCollectionFactory->create($className)->getOperation(
×
753
                            operationName: $itemUriTemplate,
×
754
                            forceCollection: true,
×
755
                            httpOperation: true
×
756
                        );
×
757

758
                        return $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_PATH, $operation, $childContext);
×
759
                    }
760

761
                    $attributeValue = $this->propertyAccessor->getValue($object, $attribute);
×
762

763
                    if (!is_iterable($attributeValue)) {
×
764
                        throw new UnexpectedValueException('Unexpected non-iterable value for to-many relation.');
×
765
                    }
766

767
                    $resourceClass = $this->resourceClassResolver->getResourceClass($attributeValue, $className);
×
768

769
                    $data = $this->normalizeCollectionOfRelations($propertyMetadata, $attributeValue, $resourceClass, $format, $childContext);
×
770
                    $context['data'] = $data;
×
771
                    $context['type'] = $type;
×
772

773
                    if ($this->tagCollector) {
×
774
                        $this->tagCollector->collect($context);
×
775
                    }
776

777
                    return $data;
×
778
                }
779

780
                if (
781
                    ($className = $type->getClassName())
×
782
                    && $this->resourceClassResolver->isResourceClass($className)
×
783
                ) {
784
                    $childContext = $this->createChildContext($this->createOperationContext($context, $className), $attribute, $format);
×
785
                    unset($childContext['iri'], $childContext['uri_variables'], $childContext['item_uri_template']);
×
786
                    if ('jsonld' === $format && $uriTemplate = $propertyMetadata->getUriTemplate()) {
×
787
                        $operation = $this->resourceMetadataCollectionFactory->create($className)->getOperation(
×
788
                            operationName: $uriTemplate,
×
789
                            httpOperation: true
×
790
                        );
×
791

792
                        return $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_PATH, $operation, $childContext);
×
793
                    }
794

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

797
                    if (!\is_object($attributeValue) && null !== $attributeValue) {
×
798
                        throw new UnexpectedValueException('Unexpected non-object value for to-one relation.');
×
799
                    }
800

801
                    $resourceClass = $this->resourceClassResolver->getResourceClass($attributeValue, $className);
×
802

803
                    $data = $this->normalizeRelation($propertyMetadata, $attributeValue, $resourceClass, $format, $childContext);
×
804
                    $context['data'] = $data;
×
805
                    $context['type'] = $type;
×
806

807
                    if ($this->tagCollector) {
×
808
                        $this->tagCollector->collect($context);
×
809
                    }
810

811
                    return $data;
×
812
                }
813

814
                if (!$this->serializer instanceof NormalizerInterface) {
×
815
                    throw new LogicException(\sprintf('The injected serializer must be an instance of "%s".', NormalizerInterface::class));
×
816
                }
817

818
                unset(
×
819
                    $context['resource_class'],
×
820
                    $context['force_resource_class'],
×
821
                    $context['uri_variables'],
×
822
                );
×
823

824
                // Anonymous resources
825
                if ($className) {
×
826
                    $childContext = $this->createChildContext($this->createOperationContext($context, $className), $attribute, $format);
×
827
                    $childContext['output']['gen_id'] = $propertyMetadata->getGenId() ?? true;
×
828

829
                    $attributeValue = $this->propertyAccessor->getValue($object, $attribute);
×
830

UNCOV
831
                    return $this->serializer->normalize($attributeValue, $format, $childContext);
×
832
                }
833

834
                if ('array' === $type->getBuiltinType()) {
×
UNCOV
835
                    if ($className = ($type->getCollectionValueTypes()[0] ?? null)?->getClassName()) {
×
UNCOV
836
                        $context = $this->createOperationContext($context, $className);
×
837
                    }
838

UNCOV
839
                    $childContext = $this->createChildContext($context, $attribute, $format);
×
840
                    $childContext['output']['gen_id'] = $propertyMetadata->getGenId() ?? true;
×
841

842
                    $attributeValue = $this->propertyAccessor->getValue($object, $attribute);
×
843

UNCOV
844
                    return $this->serializer->normalize($attributeValue, $format, $childContext);
×
845
                }
846
            }
847

UNCOV
848
            if (!$this->serializer instanceof NormalizerInterface) {
×
UNCOV
849
                throw new LogicException(\sprintf('The injected serializer must be an instance of "%s".', NormalizerInterface::class));
×
850
            }
851

852
            unset(
×
853
                $context['resource_class'],
×
854
                $context['force_resource_class'],
×
UNCOV
855
                $context['uri_variables']
×
856
            );
×
857

858
            $attributeValue = $this->propertyAccessor->getValue($object, $attribute);
×
859

UNCOV
860
            return $this->serializer->normalize($attributeValue, $format, $context);
×
861
        }
862

863
        $type = $propertyMetadata->getNativeType();
434✔
864

865
        $nullable = false;
434✔
866
        if ($type instanceof NullableType) {
434✔
867
            $type = $type->getWrappedType();
278✔
868
            $nullable = true;
278✔
869
        }
870

871
        // TODO check every foreach composite to see if null is an issue
872
        $types = $type instanceof CompositeTypeInterface ? $type->getTypes() : (null === $type ? [] : [$type]);
434✔
873
        $className = null;
434✔
874
        $typeIsResourceClass = function (Type $type) use (&$className): bool {
434✔
875
            return $type instanceof ObjectType && $this->resourceClassResolver->isResourceClass($className = $type->getClassName());
432✔
876
        };
434✔
877

878
        foreach ($types as $type) {
434✔
879
            if ($type instanceof CollectionType && $type->getCollectionValueType()->isSatisfiedBy($typeIsResourceClass)) {
432✔
880
                $childContext = $this->createChildContext($this->createOperationContext($context, $className, $propertyMetadata), $attribute, $format);
14✔
881

882
                // @see ApiPlatform\Hal\Serializer\ItemNormalizer:getComponents logic for intentional duplicate content
883
                // @see ApiPlatform\JsonApi\Serializer\ItemNormalizer:getComponents logic for intentional duplicate content
884
                if ('jsonld' === $format && $itemUriTemplate = $propertyMetadata->getUriTemplate()) {
14✔
885
                    $operation = $this->resourceMetadataCollectionFactory->create($className)->getOperation(
×
886
                        operationName: $itemUriTemplate,
×
887
                        forceCollection: true,
×
UNCOV
888
                        httpOperation: true
×
889
                    );
×
890

UNCOV
891
                    return $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_PATH, $operation, $childContext);
×
892
                }
893

894
                $attributeValue = $this->propertyAccessor->getValue($object, $attribute);
14✔
895

896
                if (!is_iterable($attributeValue)) {
14✔
UNCOV
897
                    throw new UnexpectedValueException('Unexpected non-iterable value for to-many relation.');
×
898
                }
899

900
                $resourceClass = $this->resourceClassResolver->getResourceClass($attributeValue, $className);
14✔
901

902
                $data = $this->normalizeCollectionOfRelations($propertyMetadata, $attributeValue, $resourceClass, $format, $childContext);
14✔
903
                $context['data'] = $data;
14✔
904
                $context['type'] = ($nullable && $type instanceof Type) ? Type::nullable($type) : $type;
14✔
905

906
                if ($this->tagCollector) {
14✔
907
                    $this->tagCollector->collect($context);
14✔
908
                }
909

910
                return $data;
14✔
911
            }
912

913
            if ($type->isSatisfiedBy($typeIsResourceClass)) {
432✔
914
                $childContext = $this->createChildContext($this->createOperationContext($context, $className, $propertyMetadata), $attribute, $format);
20✔
915
                unset($childContext['iri'], $childContext['uri_variables'], $childContext['item_uri_template']);
20✔
916
                if ('jsonld' === $format && $uriTemplate = $propertyMetadata->getUriTemplate()) {
20✔
917
                    $operation = $this->resourceMetadataCollectionFactory->create($className)->getOperation(
×
918
                        operationName: $uriTemplate,
×
UNCOV
919
                        httpOperation: true
×
920
                    );
×
921

UNCOV
922
                    return $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_PATH, $operation, $childContext);
×
923
                }
924

925
                $attributeValue = $this->propertyAccessor->getValue($object, $attribute);
20✔
926

927
                if (!\is_object($attributeValue) && null !== $attributeValue) {
20✔
UNCOV
928
                    throw new UnexpectedValueException('Unexpected non-object value for to-one relation.');
×
929
                }
930

931
                $resourceClass = $this->resourceClassResolver->getResourceClass($attributeValue, $className);
20✔
932

933
                $data = $this->normalizeRelation($propertyMetadata, $attributeValue, $resourceClass, $format, $childContext);
20✔
934
                $context['data'] = $data;
20✔
935
                $context['type'] = $nullable ? Type::nullable($type) : $type;
20✔
936

937
                if ($this->tagCollector) {
20✔
938
                    $this->tagCollector->collect($context);
12✔
939
                }
940

941
                return $data;
20✔
942
            }
943

944
            if (!$this->serializer instanceof NormalizerInterface) {
432✔
UNCOV
945
                throw new LogicException(\sprintf('The injected serializer must be an instance of "%s".', NormalizerInterface::class));
×
946
            }
947

948
            unset(
432✔
949
                $context['resource_class'],
432✔
950
                $context['force_resource_class'],
432✔
951
                $context['uri_variables'],
432✔
952
            );
432✔
953

954
            // Anonymous resources
955
            if ($className) {
432✔
956
                $childContext = $this->createChildContext($this->createOperationContext($context, $className, $propertyMetadata), $attribute, $format);
160✔
957
                $attributeValue = $this->propertyAccessor->getValue($object, $attribute);
160✔
958

959
                return $this->serializer->normalize($attributeValue, $format, $childContext);
160✔
960
            }
961

962
            if ($type instanceof CollectionType) {
426✔
963
                if (($subType = $type->getCollectionValueType()) instanceof ObjectType) {
52✔
UNCOV
964
                    $context = $this->createOperationContext($context, $subType->getClassName(), $propertyMetadata);
×
965
                }
966

967
                $childContext = $this->createChildContext($context, $attribute, $format);
52✔
968
                $attributeValue = $this->propertyAccessor->getValue($object, $attribute);
52✔
969

970
                return $this->serializer->normalize($attributeValue, $format, $childContext);
52✔
971
            }
972
        }
973

974
        if (!$this->serializer instanceof NormalizerInterface) {
428✔
UNCOV
975
            throw new LogicException(\sprintf('The injected serializer must be an instance of "%s".', NormalizerInterface::class));
×
976
        }
977

978
        unset(
428✔
979
            $context['resource_class'],
428✔
980
            $context['force_resource_class'],
428✔
981
            $context['uri_variables']
428✔
982
        );
428✔
983

984
        $attributeValue = $this->propertyAccessor->getValue($object, $attribute);
428✔
985

986
        return $this->serializer->normalize($attributeValue, $format, $context);
426✔
987
    }
988

989
    /**
990
     * Normalizes a collection of relations (to-many).
991
     *
992
     * @throws UnexpectedValueException
993
     */
994
    protected function normalizeCollectionOfRelations(ApiProperty $propertyMetadata, iterable $attributeValue, string $resourceClass, ?string $format, array $context): array
995
    {
996
        $value = [];
14✔
997
        foreach ($attributeValue as $index => $obj) {
14✔
998
            if (!\is_object($obj) && null !== $obj) {
2✔
UNCOV
999
                throw new UnexpectedValueException('Unexpected non-object element in to-many relation.');
×
1000
            }
1001

1002
            // update context, if concrete object class deviates from general relation class (e.g. in case of polymorphic resources)
1003
            $objResourceClass = $this->resourceClassResolver->getResourceClass($obj, $resourceClass);
2✔
1004
            $context['resource_class'] = $objResourceClass;
2✔
1005
            if ($this->resourceMetadataCollectionFactory) {
2✔
1006
                $context['operation'] = $this->resourceMetadataCollectionFactory->create($objResourceClass)->getOperation();
2✔
1007
            }
1008

1009
            $value[$index] = $this->normalizeRelation($propertyMetadata, $obj, $resourceClass, $format, $context);
2✔
1010
        }
1011

1012
        return $value;
14✔
1013
    }
1014

1015
    /**
1016
     * Normalizes a relation.
1017
     *
1018
     * @throws LogicException
1019
     * @throws UnexpectedValueException
1020
     */
1021
    protected function normalizeRelation(ApiProperty $propertyMetadata, ?object $relatedObject, string $resourceClass, ?string $format, array $context): \ArrayObject|array|string|null
1022
    {
1023
        if (null === $relatedObject || !empty($context['attributes']) || $propertyMetadata->isReadableLink() || false === ($context['output']['gen_id'] ?? true)) {
22✔
1024
            if (!$this->serializer instanceof NormalizerInterface) {
14✔
UNCOV
1025
                throw new LogicException(\sprintf('The injected serializer must be an instance of "%s".', NormalizerInterface::class));
×
1026
            }
1027

1028
            $relatedContext = $this->createOperationContext($context, $resourceClass, $propertyMetadata);
14✔
1029
            $normalizedRelatedObject = $this->serializer->normalize($relatedObject, $format, $relatedContext);
14✔
1030
            if (!\is_string($normalizedRelatedObject) && !\is_array($normalizedRelatedObject) && !$normalizedRelatedObject instanceof \ArrayObject && null !== $normalizedRelatedObject) {
14✔
UNCOV
1031
                throw new UnexpectedValueException('Expected normalized relation to be an IRI, array, \ArrayObject or null');
×
1032
            }
1033

1034
            return $normalizedRelatedObject;
14✔
1035
        }
1036

1037
        $context['iri'] = $iri = $this->iriConverter->getIriFromResource(resource: $relatedObject, context: $context);
8✔
1038
        $context['data'] = $iri;
8✔
1039
        $context['object'] = $relatedObject;
8✔
1040
        unset($context['property_metadata'], $context['api_attribute']);
8✔
1041

1042
        if ($this->tagCollector) {
8✔
1043
            $this->tagCollector->collect($context);
4✔
1044
        } elseif (isset($context['resources'])) {
4✔
UNCOV
1045
            $context['resources'][$iri] = $iri;
×
1046
        }
1047

1048
        $push = $propertyMetadata->getPush() ?? false;
8✔
1049
        if (isset($context['resources_to_push']) && $push) {
8✔
UNCOV
1050
            $context['resources_to_push'][$iri] = $iri;
×
1051
        }
1052

1053
        return $iri;
8✔
1054
    }
1055

1056
    private function createAttributeValue(string $attribute, mixed $value, ?string $format = null, array &$context = []): mixed
1057
    {
1058
        try {
1059
            return $this->createAndValidateAttributeValue($attribute, $value, $format, $context);
12✔
1060
        } catch (NotNormalizableValueException $exception) {
4✔
1061
            if (!isset($context['not_normalizable_value_exceptions'])) {
2✔
UNCOV
1062
                throw $exception;
×
1063
            }
1064
            $context['not_normalizable_value_exceptions'][] = $exception;
2✔
1065
            throw $exception;
2✔
1066
        }
1067
    }
1068

1069
    private function createAndValidateAttributeValue(string $attribute, mixed $value, ?string $format = null, array $context = []): mixed
1070
    {
1071
        $propertyMetadata = $this->propertyMetadataFactory->create($context['resource_class'], $attribute, $this->getFactoryOptions($context));
12✔
1072
        $denormalizationException = null;
12✔
1073

1074
        $types = [];
12✔
1075
        $type = null;
12✔
1076
        if (!method_exists(PropertyInfoExtractor::class, 'getType')) {
12✔
UNCOV
1077
            $types = $propertyMetadata->getBuiltinTypes() ?? [];
×
1078
        } else {
1079
            $type = $propertyMetadata->getNativeType();
12✔
1080
            $types = $type instanceof CompositeTypeInterface ? $type->getTypes() : (null === $type ? [] : [$type]);
12✔
1081
        }
1082

1083
        $isMultipleTypes = \count($types) > 1;
12✔
1084
        $className = null;
12✔
1085
        $typeIsResourceClass = function (Type $type) use (&$className): bool {
12✔
1086
            return $type instanceof ObjectType ? $this->resourceClassResolver->isResourceClass($className = $type->getClassName()) : false;
12✔
1087
        };
12✔
1088

1089
        $isMultipleTypes = \count($types) > 1;
12✔
1090
        $denormalizationException = null;
12✔
1091

1092
        foreach ($types as $t) {
12✔
1093
            if ($type instanceof Type) {
12✔
1094
                $isNullable = $type->isNullable();
12✔
1095
            } else {
UNCOV
1096
                $isNullable = $t->isNullable();
×
1097
            }
1098

1099
            if (null === $value && ($isNullable || ($context[static::DISABLE_TYPE_ENFORCEMENT] ?? false))) {
12✔
UNCOV
1100
                return $value;
×
1101
            }
1102

1103
            $collectionValueType = null;
12✔
1104

1105
            if ($t instanceof CollectionType) {
12✔
1106
                $collectionValueType = $t->getCollectionValueType();
2✔
1107
            } elseif ($t instanceof LegacyType) {
12✔
UNCOV
1108
                $collectionValueType = $t->getCollectionValueTypes()[0] ?? null;
×
1109
            }
1110

1111
            /* From @see AbstractObjectNormalizer::validateAndDenormalize() */
1112
            // Fix a collection that contains the only one element
1113
            // This is special to xml format only
1114
            if ('xml' === $format && null !== $collectionValueType && (!\is_array($value) || !\is_int(key($value)))) {
12✔
1115
                $isMixedType = $collectionValueType instanceof Type && $collectionValueType->isIdentifiedBy(TypeIdentifier::MIXED);
×
UNCOV
1116
                if (!$isMixedType) {
×
UNCOV
1117
                    $value = [$value];
×
1118
                }
1119
            }
1120

1121
            if (($collectionValueType instanceof Type && $collectionValueType->isSatisfiedBy($typeIsResourceClass))
12✔
1122
                || ($t instanceof LegacyType && $t->isCollection() && null !== $collectionValueType && null !== ($className = $collectionValueType->getClassName()) && $this->resourceClassResolver->isResourceClass($className))
12✔
1123
            ) {
1124
                $resourceClass = $this->resourceClassResolver->getResourceClass(null, $className);
2✔
1125
                $context['resource_class'] = $resourceClass;
2✔
1126
                unset($context['uri_variables']);
2✔
1127

1128
                try {
1129
                    return $t instanceof Type
2✔
1130
                        ? $this->denormalizeObjectCollection($attribute, $propertyMetadata, $t, $resourceClass, $value, $format, $context)
2✔
UNCOV
1131
                        : $this->denormalizeCollection($attribute, $propertyMetadata, $t, $resourceClass, $value, $format, $context);
×
1132
                } catch (NotNormalizableValueException $e) {
2✔
1133
                    // union/intersect types: try the next type, if not valid, an exception will be thrown at the end
1134
                    if ($isMultipleTypes) {
2✔
1135
                        $denormalizationException ??= $e;
×
1136

UNCOV
1137
                        continue;
×
1138
                    }
1139

1140
                    throw $e;
2✔
1141
                }
1142
            }
1143

1144
            if (
1145
                ($t instanceof Type && $t->isSatisfiedBy($typeIsResourceClass))
12✔
1146
                || ($t instanceof LegacyType && null !== ($className = $t->getClassName()) && $this->resourceClassResolver->isResourceClass($className))
12✔
1147
            ) {
1148
                $resourceClass = $this->resourceClassResolver->getResourceClass(null, $className);
6✔
1149
                $childContext = $this->createChildContext($this->createOperationContext($context, $resourceClass, $propertyMetadata), $attribute, $format);
6✔
1150

1151
                try {
1152
                    return $this->denormalizeRelation($attribute, $propertyMetadata, $resourceClass, $value, $format, $childContext);
6✔
1153
                } catch (NotNormalizableValueException $e) {
4✔
1154
                    // union/intersect types: try the next type, if not valid, an exception will be thrown at the end
1155
                    if ($isMultipleTypes) {
2✔
1156
                        $denormalizationException ??= $e;
2✔
1157

1158
                        continue;
2✔
1159
                    }
1160

UNCOV
1161
                    throw $e;
×
1162
                }
1163
            }
1164

1165
            if (
1166
                ($t instanceof CollectionType && $collectionValueType instanceof ObjectType && (null !== ($className = $collectionValueType->getClassName())))
8✔
1167
                || ($t instanceof LegacyType && $t->isCollection() && null !== $collectionValueType && null !== ($className = $collectionValueType->getClassName()))
8✔
1168
            ) {
UNCOV
1169
                if (!$this->serializer instanceof DenormalizerInterface) {
×
UNCOV
1170
                    throw new LogicException(\sprintf('The injected serializer must be an instance of "%s".', DenormalizerInterface::class));
×
1171
                }
1172

UNCOV
1173
                unset($context['resource_class'], $context['uri_variables']);
×
1174

1175
                try {
UNCOV
1176
                    return $this->serializer->denormalize($value, $className.'[]', $format, $context);
×
1177
                } catch (NotNormalizableValueException $e) {
×
1178
                    // union/intersect types: try the next type, if not valid, an exception will be thrown at the end
UNCOV
1179
                    if ($isMultipleTypes) {
×
1180
                        $denormalizationException ??= $e;
×
1181

UNCOV
1182
                        continue;
×
1183
                    }
1184

UNCOV
1185
                    throw $e;
×
1186
                }
1187
            }
1188

1189
            while ($t instanceof WrappingTypeInterface) {
8✔
UNCOV
1190
                $t = $t->getWrappedType();
×
1191
            }
1192

1193
            if (
1194
                $t instanceof ObjectType
8✔
1195
                || ($t instanceof LegacyType && null !== $t->getClassName())
8✔
1196
            ) {
1197
                if (!$this->serializer instanceof DenormalizerInterface) {
2✔
UNCOV
1198
                    throw new LogicException(\sprintf('The injected serializer must be an instance of "%s".', DenormalizerInterface::class));
×
1199
                }
1200

1201
                unset($context['resource_class'], $context['uri_variables']);
2✔
1202

1203
                try {
1204
                    return $this->serializer->denormalize($value, $t->getClassName(), $format, $context);
2✔
1205
                } catch (NotNormalizableValueException $e) {
2✔
1206
                    // union/intersect types: try the next type, if not valid, an exception will be thrown at the end
1207
                    if ($isMultipleTypes) {
2✔
1208
                        $denormalizationException ??= $e;
2✔
1209

1210
                        continue;
2✔
1211
                    }
1212

UNCOV
1213
                    throw $e;
×
1214
                }
1215
            }
1216

1217
            /* From @see AbstractObjectNormalizer::validateAndDenormalize() */
1218
            // In XML and CSV all basic datatypes are represented as strings, it is e.g. not possible to determine,
1219
            // if a value is meant to be a string, float, int or a boolean value from the serialized representation.
1220
            // That's why we have to transform the values, if one of these non-string basic datatypes is expected.
1221
            if (\is_string($value) && (XmlEncoder::FORMAT === $format || CsvEncoder::FORMAT === $format)) {
8✔
1222
                if ('' === $value && $isNullable && (
×
UNCOV
1223
                    ($t instanceof Type && $t->isIdentifiedBy(TypeIdentifier::BOOL, TypeIdentifier::INT, TypeIdentifier::FLOAT))
×
1224
                    || ($t instanceof LegacyType && \in_array($t->getBuiltinType(), [LegacyType::BUILTIN_TYPE_BOOL, LegacyType::BUILTIN_TYPE_INT, LegacyType::BUILTIN_TYPE_FLOAT], true))
×
1225
                )) {
UNCOV
1226
                    return null;
×
1227
                }
1228

UNCOV
1229
                $typeIdentifier = $t instanceof BuiltinType ? $t->getTypeIdentifier() : TypeIdentifier::tryFrom($t->getBuiltinType());
×
1230

1231
                switch ($typeIdentifier) {
1232
                    case TypeIdentifier::BOOL:
×
1233
                        // according to http://www.w3.org/TR/xmlschema-2/#boolean, valid representations are "false", "true", "0" and "1"
1234
                        if ('false' === $value || '0' === $value) {
×
1235
                            $value = false;
×
UNCOV
1236
                        } elseif ('true' === $value || '1' === $value) {
×
UNCOV
1237
                            $value = true;
×
1238
                        } else {
1239
                            // union/intersect types: try the next type, if not valid, an exception will be thrown at the end
UNCOV
1240
                            if ($isMultipleTypes) {
×
1241
                                break 2;
×
1242
                            }
1243
                            throw NotNormalizableValueException::createForUnexpectedDataType(\sprintf('The type of the "%s" attribute for class "%s" must be bool ("%s" given).', $attribute, $className, $value), $value, ['bool'], $context['deserialization_path'] ?? null);
×
1244
                        }
1245
                        break;
×
1246
                    case TypeIdentifier::INT:
×
UNCOV
1247
                        if (ctype_digit($value) || ('-' === $value[0] && ctype_digit(substr($value, 1)))) {
×
UNCOV
1248
                            $value = (int) $value;
×
1249
                        } else {
1250
                            // union/intersect types: try the next type, if not valid, an exception will be thrown at the end
UNCOV
1251
                            if ($isMultipleTypes) {
×
1252
                                break 2;
×
1253
                            }
1254
                            throw NotNormalizableValueException::createForUnexpectedDataType(\sprintf('The type of the "%s" attribute for class "%s" must be int ("%s" given).', $attribute, $className, $value), $value, ['int'], $context['deserialization_path'] ?? null);
×
1255
                        }
1256
                        break;
×
1257
                    case TypeIdentifier::FLOAT:
×
UNCOV
1258
                        if (is_numeric($value)) {
×
UNCOV
1259
                            return (float) $value;
×
1260
                        }
1261

1262
                        switch ($value) {
1263
                            case 'NaN':
×
1264
                                return \NAN;
×
1265
                            case 'INF':
×
1266
                                return \INF;
×
UNCOV
1267
                            case '-INF':
×
UNCOV
1268
                                return -\INF;
×
1269
                            default:
1270
                                // union/intersect types: try the next type, if not valid, an exception will be thrown at the end
UNCOV
1271
                                if ($isMultipleTypes) {
×
1272
                                    break 3;
×
1273
                                }
UNCOV
1274
                                throw NotNormalizableValueException::createForUnexpectedDataType(\sprintf('The type of the "%s" attribute for class "%s" must be float ("%s" given).', $attribute, $className, $value), $value, ['float'], $context['deserialization_path'] ?? null);
×
1275
                        }
1276
                }
1277
            }
1278

1279
            if ($context[static::DISABLE_TYPE_ENFORCEMENT] ?? false) {
8✔
UNCOV
1280
                return $value;
×
1281
            }
1282

1283
            try {
1284
                $t instanceof Type
8✔
1285
                    ? $this->validateAttributeType($attribute, $t, $value, $format, $context)
8✔
UNCOV
1286
                    : $this->validateType($attribute, $t, $value, $format, $context);
×
1287

1288
                $denormalizationException = null;
6✔
1289
                break;
6✔
1290
            } catch (NotNormalizableValueException $e) {
2✔
1291
                // union/intersect types: try the next type
1292
                if (!$isMultipleTypes) {
2✔
UNCOV
1293
                    throw $e;
×
1294
                }
1295

1296
                $denormalizationException ??= $e;
2✔
1297
            }
1298
        }
1299

1300
        if ($denormalizationException) {
8✔
1301
            if ($type instanceof Type && $type->isSatisfiedBy(static fn ($type) => $type instanceof BuiltinType) && !$type->isSatisfiedBy($typeIsResourceClass)) {
2✔
1302
                throw NotNormalizableValueException::createForUnexpectedDataType(\sprintf('The type of the "%s" attribute must be "%s", "%s" given.', $attribute, $type, \gettype($value)), $value, array_map(strval(...), $types), $context['deserialization_path'] ?? null);
2✔
1303
            }
1304

1305
            throw $denormalizationException;
2✔
1306
        }
1307

1308
        return $value;
6✔
1309
    }
1310

1311
    /**
1312
     * Sets a value of the object using the PropertyAccess component.
1313
     */
1314
    private function setValue(object $object, string $attributeName, mixed $value): void
1315
    {
1316
        try {
1317
            $this->propertyAccessor->setValue($object, $attributeName, $value);
8✔
UNCOV
1318
        } catch (NoSuchPropertyException) {
×
1319
            // Properties not found are ignored
1320
        }
1321
    }
1322
}
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