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

api-platform / core / 14836358929

05 May 2025 12:24PM UTC coverage: 8.396% (-15.0%) from 23.443%
14836358929

push

github

soyuka
test: property info deprecation

0 of 300 new or added lines in 4 files covered. (0.0%)

2655 existing lines in 165 files now uncovered.

13444 of 160118 relevant lines covered (8.4%)

22.88 hits per line

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

71.04
/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'])) {
2,035✔
76
            $defaultContext['circular_reference_handler'] = fn ($object): ?string => $this->iriConverter->getIriFromResource($object);
2,023✔
77
        }
78

79
        parent::__construct($classMetadataFactory, $nameConverter, null, null, \Closure::fromCallable($this->getObjectClass(...)), $defaultContext);
2,035✔
80
        $this->propertyAccessor = $propertyAccessor ?: PropertyAccess::createPropertyAccessor();
2,035✔
81
        $this->resourceAccessChecker = $resourceAccessChecker;
2,035✔
82
        $this->resourceMetadataCollectionFactory = $resourceMetadataCollectionFactory;
2,035✔
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)) {
1,788✔
91
            return false;
678✔
92
        }
93

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

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

102
    public function getSupportedTypes(?string $format): array
103
    {
104
        return [
1,847✔
105
            'object' => true,
1,847✔
106
        ];
1,847✔
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);
1,734✔
117
        if ($outputClass = $this->getOutputClass($context)) {
1,734✔
118
            if (!$this->serializer instanceof NormalizerInterface) {
43✔
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']);
43✔
123
            $context['resource_class'] = $outputClass;
43✔
124
            $context['api_sub_level'] = true;
43✔
125
            $context[self::ALLOW_EXTRA_ATTRIBUTES] = false;
43✔
126

127
            return $this->serializer->normalize($object, $format, $context);
43✔
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) {
1,734✔
133
            unset($context['operation_name'], $context['operation'], $context['iri']);
16✔
134
        }
135

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

140
        $context['api_normalize'] = true;
1,734✔
141
        $iri = $context['iri'] ??= $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_URL, $context['operation'] ?? null, $context);
1,734✔
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;
1,734✔
154
        unset($context['api_empty_resource_as_iri']);
1,734✔
155

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

160
        $context['object'] = $object;
1,734✔
161
        $context['format'] = $format;
1,734✔
162

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

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

168
        if ($emptyResourceAsIri && \is_array($data) && 0 === \count($data)) {
1,734✔
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) {
1,734✔
179
            $this->tagCollector->collect($context);
1,515✔
180
        }
181

182
        return $data;
1,734✔
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) {
488✔
191
            return true;
×
192
        }
193

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

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

204
        if ($inputClass = $this->getInputClass($context)) {
482✔
205
            if (!$this->serializer instanceof DenormalizerInterface) {
25✔
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']);
25✔
210
            $context['resource_class'] = $inputClass;
25✔
211

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

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

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

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

231
        if (\is_string($data)) {
462✔
232
            try {
233
                return $this->iriConverter->getResourceFromIri($data, $context + ['fetch_data' => true]);
5✔
234
            } catch (ItemNotFoundException $e) {
×
235
                throw new UnexpectedValueException($e->getMessage(), $e->getCode(), $e);
×
236
            } catch (InvalidArgumentException $e) {
×
237
                throw new UnexpectedValueException(\sprintf('Invalid IRI "%s".', $data), $e->getCode(), $e);
×
238
            }
239
        }
240

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

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

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

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

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

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

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

278
        return $object;
428✔
279
    }
280

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

UNCOV
294
            return $object;
97✔
295
        }
296

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

UNCOV
393
        return $mappedClass;
2✔
394
    }
395

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

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

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

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

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

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

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

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

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

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

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

474
        return true;
1,686✔
475
    }
476

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

493
        return true;
387✔
494
    }
495

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

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

522
        $builtinType = $type->getBuiltinType();
×
523
        if (LegacyType::BUILTIN_TYPE_FLOAT === $builtinType && null !== $format && str_contains($format, 'json')) {
×
524
            $isValid = \is_float($value) || \is_int($value);
×
525
        } else {
526
            $isValid = \call_user_func('is_'.$builtinType, $value);
×
527
        }
528

529
        if (!$isValid) {
×
530
            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);
×
531
        }
532
    }
533

534
    /**
535
     * Validates the type of the value. Allows using integers as floats for JSON formats.
536
     *
537
     * @throws NotNormalizableValueException
538
     */
539
    protected function validateAttributeType(string $attribute, Type $type, mixed $value, ?string $format = null, array $context = []): void
540
    {
541
        if ($type->isIdentifiedBy(TypeIdentifier::FLOAT) && null !== $format && str_contains($format, 'json')) {
342✔
UNCOV
542
            $isValid = \is_float($value) || \is_int($value);
2✔
543
        } else {
544
            $isValid = $type->accepts($value);
342✔
545
        }
546

547
        if (!$isValid) {
342✔
548
            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);
76✔
549
        }
550
    }
551

552
    /**
553
     * @deprecated since 4.1, use "denormalizeObjectCollection" instead.
554
     *
555
     * Denormalizes a collection of objects.
556
     *
557
     * @throws NotNormalizableValueException
558
     */
559
    protected function denormalizeCollection(string $attribute, ApiProperty $propertyMetadata, LegacyType $type, string $className, mixed $value, ?string $format, array $context): array
560
    {
561
        trigger_deprecation('api-platform/serializer', '4.1', 'The "%s()" method is deprecated, use "%s::denormalizeObjectCollection()" instead.', __METHOD__, self::class);
×
562

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

567
        $values = [];
×
568
        $childContext = $this->createChildContext($this->createOperationContext($context, $className), $attribute, $format);
×
569
        $collectionKeyTypes = $type->getCollectionKeyTypes();
×
570
        foreach ($value as $index => $obj) {
×
571
            $currentChildContext = $childContext;
×
572
            if (isset($childContext['deserialization_path'])) {
×
573
                $currentChildContext['deserialization_path'] = "{$childContext['deserialization_path']}[{$index}]";
×
574
            }
575

576
            // no typehint provided on collection key
577
            if (!$collectionKeyTypes) {
×
578
                $values[$index] = $this->denormalizeRelation($attribute, $propertyMetadata, $className, $obj, $format, $currentChildContext);
×
579
                continue;
×
580
            }
581

582
            // validate collection key typehint
583
            foreach ($collectionKeyTypes as $collectionKeyType) {
×
584
                $collectionKeyBuiltinType = $collectionKeyType->getBuiltinType();
×
585
                if (!\call_user_func('is_'.$collectionKeyBuiltinType, $index)) {
×
586
                    continue;
×
587
                }
588

589
                $values[$index] = $this->denormalizeRelation($attribute, $propertyMetadata, $className, $obj, $format, $currentChildContext);
×
590
                continue 2;
×
591
            }
592
            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);
×
593
        }
594

595
        return $values;
×
596
    }
597

598
    /**
599
     * Denormalizes a collection of objects.
600
     *
601
     * @throws NotNormalizableValueException
602
     */
603
    protected function denormalizeObjectCollection(string $attribute, ApiProperty $propertyMetadata, Type $type, string $className, mixed $value, ?string $format, array $context): array
604
    {
605
        if (!\is_array($value)) {
32✔
606
            throw NotNormalizableValueException::createForUnexpectedDataType(\sprintf('The type of the "%s" attribute must be "array", "%s" given.', $attribute, \gettype($value)), $value, ['array'], $context['deserialization_path'] ?? null);
4✔
607
        }
608

UNCOV
609
        $values = [];
28✔
UNCOV
610
        $childContext = $this->createChildContext($this->createOperationContext($context, $className), $attribute, $format);
28✔
611

UNCOV
612
        foreach ($value as $index => $obj) {
28✔
UNCOV
613
            $currentChildContext = $childContext;
28✔
UNCOV
614
            if (isset($childContext['deserialization_path'])) {
28✔
UNCOV
615
                $currentChildContext['deserialization_path'] = "{$childContext['deserialization_path']}[{$index}]";
28✔
616
            }
617

UNCOV
618
            if ($type instanceof CollectionType) {
28✔
UNCOV
619
                $collectionKeyType = $type->getCollectionKeyType();
28✔
620

UNCOV
621
                while ($collectionKeyType instanceof WrappingTypeInterface) {
28✔
622
                    $collectionKeyType = $type->getWrappedType();
×
623
                }
624

UNCOV
625
                if (!$collectionKeyType->accepts($index)) {
28✔
UNCOV
626
                    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);
2✔
627
                }
628
            }
629

UNCOV
630
            $values[$index] = $this->denormalizeRelation($attribute, $propertyMetadata, $className, $obj, $format, $currentChildContext);
26✔
631
        }
632

UNCOV
633
        return $values;
26✔
634
    }
635

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

662
                return null;
×
UNCOV
663
            } catch (InvalidArgumentException $e) {
4✔
UNCOV
664
                if (!isset($context['not_normalizable_value_exceptions'])) {
4✔
UNCOV
665
                    throw new UnexpectedValueException(\sprintf('Invalid IRI "%s".', $value), $e->getCode(), $e);
4✔
666
                }
667
                $context['not_normalizable_value_exceptions'][] = NotNormalizableValueException::createForUnexpectedDataType(
×
668
                    $e->getMessage(),
×
669
                    $value,
×
670
                    [$className],
×
671
                    $context['deserialization_path'] ?? null,
×
672
                    true,
×
673
                    $e->getCode(),
×
674
                    $e
×
675
                );
×
676

677
                return null;
×
678
            }
679
        }
680

681
        if ($propertyMetadata->isWritableLink()) {
52✔
UNCOV
682
            $context['api_allow_update'] = true;
49✔
683

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

UNCOV
688
            $item = $this->serializer->denormalize($value, $className, $format, $context);
49✔
UNCOV
689
            if (!\is_object($item) && null !== $item) {
45✔
690
                throw new \UnexpectedValueException('Expected item to be an object or null.');
×
691
            }
692

UNCOV
693
            return $item;
45✔
694
        }
695

696
        if (!\is_array($value)) {
3✔
697
            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✔
698
        }
699

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

703
    /**
704
     * Gets the options for the property name collection / property metadata factories.
705
     */
706
    protected function getFactoryOptions(array $context): array
707
    {
708
        $options = [];
1,748✔
709
        if (isset($context[self::GROUPS])) {
1,748✔
710
            /* @see https://github.com/symfony/symfony/blob/v4.2.6/src/Symfony/Component/PropertyInfo/Extractor/SerializerExtractor.php */
711
            $options['serializer_groups'] = (array) $context[self::GROUPS];
596✔
712
        }
713

714
        $operationCacheKey = ($context['resource_class'] ?? '').($context['operation_name'] ?? '').($context['root_operation_name'] ?? '');
1,748✔
715
        $suffix = ($context['api_normalize'] ?? '') ? 'n' : '';
1,748✔
716
        if ($operationCacheKey && isset($this->localFactoryOptionsCache[$operationCacheKey.$suffix])) {
1,748✔
717
            return $options + $this->localFactoryOptionsCache[$operationCacheKey.$suffix];
1,732✔
718
        }
719

720
        // This is a hot spot
721
        if (isset($context['resource_class'])) {
1,748✔
722
            // Note that the groups need to be read on the root operation
723
            if ($operation = ($context['root_operation'] ?? null)) {
1,748✔
724
                $options['normalization_groups'] = $operation->getNormalizationContext()['groups'] ?? null;
741✔
725
                $options['denormalization_groups'] = $operation->getDenormalizationContext()['groups'] ?? null;
741✔
726
                $options['operation_name'] = $operation->getName();
741✔
727
            }
728
        }
729

730
        return $options + $this->localFactoryOptionsCache[$operationCacheKey.$suffix] = $options;
1,748✔
731
    }
732

733
    /**
734
     * {@inheritdoc}
735
     *
736
     * @throws UnexpectedValueException
737
     */
738
    protected function getAttributeValue(object $object, string $attribute, ?string $format = null, array $context = []): mixed
739
    {
740
        $context['api_attribute'] = $attribute;
1,706✔
741
        $context['property_metadata'] = $propertyMetadata = $this->propertyMetadataFactory->create($context['resource_class'], $attribute, $this->getFactoryOptions($context));
1,706✔
742

743
        if ($context['api_denormalize'] ?? false) {
1,706✔
UNCOV
744
            return $this->propertyAccessor->getValue($object, $attribute);
21✔
745
        }
746

747
        if (!method_exists(PropertyInfoExtractor::class, 'getType')) {
1,706✔
748
            $types = $propertyMetadata->getBuiltinTypes() ?? [];
×
749

750
            foreach ($types as $type) {
×
751
                if (
752
                    $type->isCollection()
×
753
                    && ($collectionValueType = $type->getCollectionValueTypes()[0] ?? null)
×
754
                    && ($className = $collectionValueType->getClassName())
×
755
                    && $this->resourceClassResolver->isResourceClass($className)
×
756
                ) {
757
                    $childContext = $this->createChildContext($this->createOperationContext($context, $className), $attribute, $format);
×
758

759
                    // @see ApiPlatform\Hal\Serializer\ItemNormalizer:getComponents logic for intentional duplicate content
760
                    // @see ApiPlatform\JsonApi\Serializer\ItemNormalizer:getComponents logic for intentional duplicate content
761
                    if ('jsonld' === $format && $itemUriTemplate = $propertyMetadata->getUriTemplate()) {
×
762
                        $operation = $this->resourceMetadataCollectionFactory->create($className)->getOperation(
×
763
                            operationName: $itemUriTemplate,
×
764
                            forceCollection: true,
×
765
                            httpOperation: true
×
766
                        );
×
767

768
                        return $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_PATH, $operation, $childContext);
×
769
                    }
770

771
                    $attributeValue = $this->propertyAccessor->getValue($object, $attribute);
×
772

773
                    if (!is_iterable($attributeValue)) {
×
774
                        throw new UnexpectedValueException('Unexpected non-iterable value for to-many relation.');
×
775
                    }
776

777
                    $resourceClass = $this->resourceClassResolver->getResourceClass($attributeValue, $className);
×
778

779
                    $data = $this->normalizeCollectionOfRelations($propertyMetadata, $attributeValue, $resourceClass, $format, $childContext);
×
780
                    $context['data'] = $data;
×
781
                    $context['type'] = $type;
×
782

783
                    if ($this->tagCollector) {
×
784
                        $this->tagCollector->collect($context);
×
785
                    }
786

787
                    return $data;
×
788
                }
789

790
                if (
791
                    ($className = $type->getClassName())
×
792
                    && $this->resourceClassResolver->isResourceClass($className)
×
793
                ) {
794
                    $childContext = $this->createChildContext($this->createOperationContext($context, $className), $attribute, $format);
×
795
                    unset($childContext['iri'], $childContext['uri_variables'], $childContext['item_uri_template']);
×
796
                    if ('jsonld' === $format && $uriTemplate = $propertyMetadata->getUriTemplate()) {
×
797
                        $operation = $this->resourceMetadataCollectionFactory->create($className)->getOperation(
×
798
                            operationName: $uriTemplate,
×
799
                            httpOperation: true
×
800
                        );
×
801

802
                        return $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_PATH, $operation, $childContext);
×
803
                    }
804

805
                    $attributeValue = $this->propertyAccessor->getValue($object, $attribute);
×
806

807
                    if (!\is_object($attributeValue) && null !== $attributeValue) {
×
808
                        throw new UnexpectedValueException('Unexpected non-object value for to-one relation.');
×
809
                    }
810

811
                    $resourceClass = $this->resourceClassResolver->getResourceClass($attributeValue, $className);
×
812

813
                    $data = $this->normalizeRelation($propertyMetadata, $attributeValue, $resourceClass, $format, $childContext);
×
814
                    $context['data'] = $data;
×
815
                    $context['type'] = $type;
×
816

817
                    if ($this->tagCollector) {
×
818
                        $this->tagCollector->collect($context);
×
819
                    }
820

821
                    return $data;
×
822
                }
823

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

828
                unset(
×
829
                    $context['resource_class'],
×
830
                    $context['force_resource_class'],
×
831
                    $context['uri_variables'],
×
832
                );
×
833

834
                // Anonymous resources
835
                if ($className) {
×
836
                    $childContext = $this->createChildContext($this->createOperationContext($context, $className), $attribute, $format);
×
837
                    $childContext['output']['gen_id'] = $propertyMetadata->getGenId() ?? true;
×
838

839
                    $attributeValue = $this->propertyAccessor->getValue($object, $attribute);
×
840

841
                    return $this->serializer->normalize($attributeValue, $format, $childContext);
×
842
                }
843

844
                if ('array' === $type->getBuiltinType()) {
×
845
                    if ($className = ($type->getCollectionValueTypes()[0] ?? null)?->getClassName()) {
×
846
                        $context = $this->createOperationContext($context, $className);
×
847
                    }
848

849
                    $childContext = $this->createChildContext($context, $attribute, $format);
×
850
                    $childContext['output']['gen_id'] = $propertyMetadata->getGenId() ?? true;
×
851

852
                    $attributeValue = $this->propertyAccessor->getValue($object, $attribute);
×
853

854
                    return $this->serializer->normalize($attributeValue, $format, $childContext);
×
855
                }
856
            }
857

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

862
            unset(
×
863
                $context['resource_class'],
×
864
                $context['force_resource_class'],
×
865
                $context['uri_variables']
×
866
            );
×
867

868
            $attributeValue = $this->propertyAccessor->getValue($object, $attribute);
×
869

870
            return $this->serializer->normalize($attributeValue, $format, $context);
×
871
        }
872

873
        $type = $propertyMetadata->getNativeType();
1,706✔
874

875
        $nullable = false;
1,706✔
876
        if ($type instanceof NullableType) {
1,706✔
877
            $type = $type->getWrappedType();
1,106✔
878
            $nullable = true;
1,106✔
879
        }
880

881
        // TODO check every foreach composite to see if null is an issue
882
        $types = $type instanceof CompositeTypeInterface ? $type->getTypes() : (null === $type ? [] : [$type]);
1,706✔
883
        $className = null;
1,706✔
884
        $typeIsResourceClass = function (Type $type) use (&$className): bool {
1,706✔
885
            return $type instanceof ObjectType && $this->resourceClassResolver->isResourceClass($className = $type->getClassName());
1,674✔
886
        };
1,706✔
887

888
        foreach ($types as $type) {
1,706✔
889
            if ($type instanceof CollectionType && $type->getCollectionValueType()->isSatisfiedBy($typeIsResourceClass)) {
1,674✔
890
                $childContext = $this->createChildContext($this->createOperationContext($context, $className), $attribute, $format);
433✔
891

892
                // @see ApiPlatform\Hal\Serializer\ItemNormalizer:getComponents logic for intentional duplicate content
893
                // @see ApiPlatform\JsonApi\Serializer\ItemNormalizer:getComponents logic for intentional duplicate content
894
                if ('jsonld' === $format && $itemUriTemplate = $propertyMetadata->getUriTemplate()) {
433✔
UNCOV
895
                    $operation = $this->resourceMetadataCollectionFactory->create($className)->getOperation(
2✔
UNCOV
896
                        operationName: $itemUriTemplate,
2✔
UNCOV
897
                        forceCollection: true,
2✔
UNCOV
898
                        httpOperation: true
2✔
UNCOV
899
                    );
2✔
900

UNCOV
901
                    return $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_PATH, $operation, $childContext);
2✔
902
                }
903

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

906
                if (!is_iterable($attributeValue)) {
431✔
907
                    throw new UnexpectedValueException('Unexpected non-iterable value for to-many relation.');
×
908
                }
909

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

912
                $data = $this->normalizeCollectionOfRelations($propertyMetadata, $attributeValue, $resourceClass, $format, $childContext);
431✔
913
                $context['data'] = $data;
431✔
914
                $context['type'] = ($nullable && $type instanceof Type) ? Type::nullable($type) : $type;
431✔
915

916
                if ($this->tagCollector) {
431✔
917
                    $this->tagCollector->collect($context);
392✔
918
                }
919

920
                return $data;
431✔
921
            }
922

923
            if ($type->isSatisfiedBy($typeIsResourceClass)) {
1,674✔
924
                $childContext = $this->createChildContext($this->createOperationContext($context, $className), $attribute, $format);
605✔
925
                unset($childContext['iri'], $childContext['uri_variables'], $childContext['item_uri_template']);
605✔
926
                if ('jsonld' === $format && $uriTemplate = $propertyMetadata->getUriTemplate()) {
605✔
UNCOV
927
                    $operation = $this->resourceMetadataCollectionFactory->create($className)->getOperation(
2✔
UNCOV
928
                        operationName: $uriTemplate,
2✔
UNCOV
929
                        httpOperation: true
2✔
UNCOV
930
                    );
2✔
931

UNCOV
932
                    return $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_PATH, $operation, $childContext);
2✔
933
                }
934

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

937
                if (!\is_object($attributeValue) && null !== $attributeValue) {
599✔
938
                    throw new UnexpectedValueException('Unexpected non-object value for to-one relation.');
×
939
                }
940

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

943
                $data = $this->normalizeRelation($propertyMetadata, $attributeValue, $resourceClass, $format, $childContext);
599✔
944
                $context['data'] = $data;
599✔
945
                $context['type'] = $nullable ? Type::nullable($type) : $type;
599✔
946

947
                if ($this->tagCollector) {
599✔
948
                    $this->tagCollector->collect($context);
558✔
949
                }
950

951
                return $data;
599✔
952
            }
953

954
            if (!$this->serializer instanceof NormalizerInterface) {
1,660✔
955
                throw new LogicException(\sprintf('The injected serializer must be an instance of "%s".', NormalizerInterface::class));
×
956
            }
957

958
            unset(
1,660✔
959
                $context['resource_class'],
1,660✔
960
                $context['force_resource_class'],
1,660✔
961
                $context['uri_variables'],
1,660✔
962
            );
1,660✔
963

964
            // Anonymous resources
965
            if ($className) {
1,660✔
966
                $childContext = $this->createChildContext($this->createOperationContext($context, $className), $attribute, $format);
527✔
967
                $childContext['output']['gen_id'] = $propertyMetadata->getGenId() ?? true;
527✔
968

969
                $attributeValue = $this->propertyAccessor->getValue($object, $attribute);
527✔
970

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

974
            if ($type instanceof CollectionType) {
1,641✔
975
                if (($subType = $type->getCollectionValueType()) instanceof ObjectType) {
397✔
976
                    $context = $this->createOperationContext($context, $subType->getClassName());
×
977
                }
978

979
                $childContext = $this->createChildContext($context, $attribute, $format);
397✔
980
                $childContext['output']['gen_id'] = $propertyMetadata->getGenId() ?? true;
397✔
981

982
                $attributeValue = $this->propertyAccessor->getValue($object, $attribute);
397✔
983

984
                return $this->serializer->normalize($attributeValue, $format, $childContext);
397✔
985
            }
986
        }
987

988
        if (!$this->serializer instanceof NormalizerInterface) {
1,673✔
989
            throw new LogicException(\sprintf('The injected serializer must be an instance of "%s".', NormalizerInterface::class));
×
990
        }
991

992
        unset(
1,673✔
993
            $context['resource_class'],
1,673✔
994
            $context['force_resource_class'],
1,673✔
995
            $context['uri_variables']
1,673✔
996
        );
1,673✔
997

998
        $attributeValue = $this->propertyAccessor->getValue($object, $attribute);
1,673✔
999

1000
        return $this->serializer->normalize($attributeValue, $format, $context);
1,670✔
1001
    }
1002

1003
    /**
1004
     * Normalizes a collection of relations (to-many).
1005
     *
1006
     * @throws UnexpectedValueException
1007
     */
1008
    protected function normalizeCollectionOfRelations(ApiProperty $propertyMetadata, iterable $attributeValue, string $resourceClass, ?string $format, array $context): array
1009
    {
1010
        $value = [];
392✔
1011
        foreach ($attributeValue as $index => $obj) {
392✔
1012
            if (!\is_object($obj) && null !== $obj) {
105✔
1013
                throw new UnexpectedValueException('Unexpected non-object element in to-many relation.');
×
1014
            }
1015

1016
            // update context, if concrete object class deviates from general relation class (e.g. in case of polymorphic resources)
1017
            $objResourceClass = $this->resourceClassResolver->getResourceClass($obj, $resourceClass);
105✔
1018
            $context['resource_class'] = $objResourceClass;
105✔
1019
            if ($this->resourceMetadataCollectionFactory) {
105✔
1020
                $context['operation'] = $this->resourceMetadataCollectionFactory->create($objResourceClass)->getOperation();
105✔
1021
            }
1022

1023
            $value[$index] = $this->normalizeRelation($propertyMetadata, $obj, $resourceClass, $format, $context);
105✔
1024
        }
1025

1026
        return $value;
392✔
1027
    }
1028

1029
    /**
1030
     * Normalizes a relation.
1031
     *
1032
     * @throws LogicException
1033
     * @throws UnexpectedValueException
1034
     */
1035
    protected function normalizeRelation(ApiProperty $propertyMetadata, ?object $relatedObject, string $resourceClass, ?string $format, array $context): \ArrayObject|array|string|null
1036
    {
1037
        if (null === $relatedObject || !empty($context['attributes']) || $propertyMetadata->isReadableLink()) {
537✔
1038
            if (!$this->serializer instanceof NormalizerInterface) {
419✔
1039
                throw new LogicException(\sprintf('The injected serializer must be an instance of "%s".', NormalizerInterface::class));
×
1040
            }
1041

1042
            $relatedContext = $this->createOperationContext($context, $resourceClass);
419✔
1043
            $normalizedRelatedObject = $this->serializer->normalize($relatedObject, $format, $relatedContext);
419✔
1044
            if (!\is_string($normalizedRelatedObject) && !\is_array($normalizedRelatedObject) && !$normalizedRelatedObject instanceof \ArrayObject && null !== $normalizedRelatedObject) {
419✔
1045
                throw new UnexpectedValueException('Expected normalized relation to be an IRI, array, \ArrayObject or null');
×
1046
            }
1047

1048
            return $normalizedRelatedObject;
419✔
1049
        }
1050

1051
        $context['iri'] = $iri = $this->iriConverter->getIriFromResource(resource: $relatedObject, context: $context);
176✔
1052
        $context['data'] = $iri;
176✔
1053
        $context['object'] = $relatedObject;
176✔
1054
        unset($context['property_metadata'], $context['api_attribute']);
176✔
1055

1056
        if ($this->tagCollector) {
176✔
1057
            $this->tagCollector->collect($context);
172✔
1058
        } elseif (isset($context['resources'])) {
4✔
1059
            $context['resources'][$iri] = $iri;
×
1060
        }
1061

1062
        $push = $propertyMetadata->getPush() ?? false;
176✔
1063
        if (isset($context['resources_to_push']) && $push) {
176✔
1064
            $context['resources_to_push'][$iri] = $iri;
17✔
1065
        }
1066

1067
        return $iri;
176✔
1068
    }
1069

1070
    private function createAttributeValue(string $attribute, mixed $value, ?string $format = null, array &$context = []): mixed
1071
    {
1072
        try {
1073
            return $this->createAndValidateAttributeValue($attribute, $value, $format, $context);
390✔
1074
        } catch (NotNormalizableValueException $exception) {
29✔
1075
            if (!isset($context['not_normalizable_value_exceptions'])) {
21✔
UNCOV
1076
                throw $exception;
19✔
1077
            }
1078
            $context['not_normalizable_value_exceptions'][] = $exception;
2✔
1079
            throw $exception;
2✔
1080
        }
1081
    }
1082

1083
    private function createAndValidateAttributeValue(string $attribute, mixed $value, ?string $format = null, array $context = []): mixed
1084
    {
1085
        $propertyMetadata = $this->propertyMetadataFactory->create($context['resource_class'], $attribute, $this->getFactoryOptions($context));
412✔
1086
        $denormalizationException = null;
412✔
1087

1088
        $types = [];
412✔
1089
        $type = null;
412✔
1090
        if (!method_exists(PropertyInfoExtractor::class, 'getType')) {
412✔
UNCOV
1091
            $types = $propertyMetadata->getBuiltinTypes() ?? [];
×
1092
        } else {
1093
            $type = $propertyMetadata->getNativeType();
412✔
1094
            $types = $type instanceof CompositeTypeInterface ? $type->getTypes() : (null === $type ? [] : [$type]);
412✔
1095
        }
1096

1097
        $isMultipleTypes = \count($types) > 1;
412✔
1098
        $className = null;
412✔
1099
        $typeIsResourceClass = function (Type $type) use (&$className): bool {
412✔
1100
            return $type instanceof ObjectType ? $this->resourceClassResolver->isResourceClass($className = $type->getClassName()) : false;
403✔
1101
        };
412✔
1102

1103
        $isMultipleTypes = \count($types) > 1;
412✔
1104
        $denormalizationException = null;
412✔
1105

1106
        foreach ($types as $t) {
412✔
1107
            if ($type instanceof Type) {
404✔
1108
                $isNullable = $type->isNullable();
404✔
1109
            } else {
UNCOV
1110
                $isNullable = $t->isNullable();
×
1111
            }
1112

1113
            if (null === $value && ($isNullable || ($context[static::DISABLE_TYPE_ENFORCEMENT] ?? false))) {
404✔
UNCOV
1114
                return $value;
5✔
1115
            }
1116

1117
            $collectionValueType = null;
403✔
1118

1119
            if ($t instanceof CollectionType) {
403✔
1120
                $collectionValueType = $t->getCollectionValueType();
48✔
1121
            } elseif ($t instanceof LegacyType) {
393✔
UNCOV
1122
                $collectionValueType = $t->getCollectionValueTypes()[0] ?? null;
×
1123
            }
1124

1125
            /* From @see AbstractObjectNormalizer::validateAndDenormalize() */
1126
            // Fix a collection that contains the only one element
1127
            // This is special to xml format only
1128
            if ('xml' === $format && null !== $collectionValueType && (!\is_array($value) || !\is_int(key($value)))) {
403✔
UNCOV
1129
                $isMixedType = $collectionValueType instanceof Type && $collectionValueType->isIdentifiedBy(TypeIdentifier::MIXED);
2✔
UNCOV
1130
                if (!$isMixedType) {
2✔
UNCOV
1131
                    $value = [$value];
2✔
1132
                }
1133
            }
1134

1135
            if (($collectionValueType instanceof Type && $collectionValueType->isSatisfiedBy($typeIsResourceClass))
403✔
1136
                || ($t instanceof LegacyType && $t->isCollection() && null !== $collectionValueType && null !== ($className = $collectionValueType->getClassName()) && $this->resourceClassResolver->isResourceClass($className))
403✔
1137
            ) {
1138
                $resourceClass = $this->resourceClassResolver->getResourceClass(null, $className);
32✔
1139
                $context['resource_class'] = $resourceClass;
32✔
1140
                unset($context['uri_variables']);
32✔
1141

1142
                try {
1143
                    return $t instanceof Type
32✔
1144
                        ? $this->denormalizeObjectCollection($attribute, $propertyMetadata, $t, $resourceClass, $value, $format, $context)
32✔
UNCOV
1145
                        : $this->denormalizeCollection($attribute, $propertyMetadata, $t, $resourceClass, $value, $format, $context);
26✔
1146
                } catch (NotNormalizableValueException $e) {
6✔
1147
                    // union/intersect types: try the next type, if not valid, an exception will be thrown at the end
1148
                    if ($isMultipleTypes) {
6✔
1149
                        $denormalizationException ??= $e;
×
1150

UNCOV
1151
                        continue;
×
1152
                    }
1153

1154
                    throw $e;
6✔
1155
                }
1156
            }
1157

1158
            if (
1159
                ($t instanceof Type && $t->isSatisfiedBy($typeIsResourceClass))
394✔
1160
                || ($t instanceof LegacyType && null !== ($className = $t->getClassName()) && $this->resourceClassResolver->isResourceClass($className))
394✔
1161
            ) {
1162
                $resourceClass = $this->resourceClassResolver->getResourceClass(null, $className);
104✔
1163
                $childContext = $this->createChildContext($this->createOperationContext($context, $resourceClass), $attribute, $format);
104✔
1164

1165
                try {
1166
                    return $this->denormalizeRelation($attribute, $propertyMetadata, $resourceClass, $value, $format, $childContext);
104✔
1167
                } catch (NotNormalizableValueException $e) {
13✔
1168
                    // union/intersect types: try the next type, if not valid, an exception will be thrown at the end
1169
                    if ($isMultipleTypes) {
5✔
1170
                        $denormalizationException ??= $e;
4✔
1171

1172
                        continue;
4✔
1173
                    }
1174

UNCOV
1175
                    throw $e;
1✔
1176
                }
1177
            }
1178

1179
            if (
1180
                ($t instanceof CollectionType && $collectionValueType instanceof ObjectType && (null !== ($className = $collectionValueType->getClassName())))
362✔
1181
                || ($t instanceof LegacyType && $t->isCollection() && null !== $collectionValueType && null !== ($className = $collectionValueType->getClassName()))
362✔
1182
            ) {
UNCOV
1183
                if (!$this->serializer instanceof DenormalizerInterface) {
6✔
UNCOV
1184
                    throw new LogicException(\sprintf('The injected serializer must be an instance of "%s".', DenormalizerInterface::class));
×
1185
                }
1186

UNCOV
1187
                unset($context['resource_class'], $context['uri_variables']);
6✔
1188

1189
                try {
UNCOV
1190
                    return $this->serializer->denormalize($value, $className.'[]', $format, $context);
6✔
1191
                } catch (NotNormalizableValueException $e) {
×
1192
                    // union/intersect types: try the next type, if not valid, an exception will be thrown at the end
UNCOV
1193
                    if ($isMultipleTypes) {
×
1194
                        $denormalizationException ??= $e;
×
1195

UNCOV
1196
                        continue;
×
1197
                    }
1198

UNCOV
1199
                    throw $e;
×
1200
                }
1201
            }
1202

1203
            while ($t instanceof WrappingTypeInterface) {
362✔
UNCOV
1204
                $t = $t->getWrappedType();
11✔
1205
            }
1206

1207
            if (
1208
                $t instanceof ObjectType
362✔
1209
                || ($t instanceof LegacyType && null !== $t->getClassName())
362✔
1210
            ) {
1211
                if (!$this->serializer instanceof DenormalizerInterface) {
36✔
UNCOV
1212
                    throw new LogicException(\sprintf('The injected serializer must be an instance of "%s".', DenormalizerInterface::class));
×
1213
                }
1214

1215
                unset($context['resource_class'], $context['uri_variables']);
36✔
1216

1217
                try {
1218
                    return $this->serializer->denormalize($value, $t->getClassName(), $format, $context);
36✔
1219
                } catch (NotNormalizableValueException $e) {
11✔
1220
                    // union/intersect types: try the next type, if not valid, an exception will be thrown at the end
1221
                    if ($isMultipleTypes) {
11✔
1222
                        $denormalizationException ??= $e;
9✔
1223

1224
                        continue;
9✔
1225
                    }
1226

UNCOV
1227
                    throw $e;
2✔
1228
                }
1229
            }
1230

1231
            /* From @see AbstractObjectNormalizer::validateAndDenormalize() */
1232
            // In XML and CSV all basic datatypes are represented as strings, it is e.g. not possible to determine,
1233
            // if a value is meant to be a string, float, int or a boolean value from the serialized representation.
1234
            // That's why we have to transform the values, if one of these non-string basic datatypes is expected.
1235
            if (\is_string($value) && (XmlEncoder::FORMAT === $format || CsvEncoder::FORMAT === $format)) {
350✔
UNCOV
1236
                if ('' === $value && $isNullable && (
30✔
UNCOV
1237
                    ($t instanceof Type && $t->isIdentifiedBy(TypeIdentifier::BOOL, TypeIdentifier::INT, TypeIdentifier::FLOAT))
30✔
1238
                    || ($t instanceof LegacyType && \in_array($t->getBuiltinType(), [LegacyType::BUILTIN_TYPE_BOOL, LegacyType::BUILTIN_TYPE_INT, LegacyType::BUILTIN_TYPE_FLOAT], true))
30✔
1239
                )) {
UNCOV
1240
                    return null;
×
1241
                }
1242

UNCOV
1243
                $typeIdentifier = $t instanceof BuiltinType ? $t->getTypeIdentifier() : TypeIdentifier::tryFrom($t->getBuiltinType());
30✔
1244

1245
                switch ($typeIdentifier) {
UNCOV
1246
                    case TypeIdentifier::BOOL:
30✔
1247
                        // according to http://www.w3.org/TR/xmlschema-2/#boolean, valid representations are "false", "true", "0" and "1"
UNCOV
1248
                        if ('false' === $value || '0' === $value) {
8✔
UNCOV
1249
                            $value = false;
4✔
UNCOV
1250
                        } elseif ('true' === $value || '1' === $value) {
4✔
UNCOV
1251
                            $value = true;
4✔
1252
                        } else {
1253
                            // union/intersect types: try the next type, if not valid, an exception will be thrown at the end
UNCOV
1254
                            if ($isMultipleTypes) {
×
1255
                                break 2;
×
1256
                            }
UNCOV
1257
                            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);
×
1258
                        }
UNCOV
1259
                        break;
8✔
UNCOV
1260
                    case TypeIdentifier::INT:
22✔
UNCOV
1261
                        if (ctype_digit($value) || ('-' === $value[0] && ctype_digit(substr($value, 1)))) {
8✔
UNCOV
1262
                            $value = (int) $value;
8✔
1263
                        } else {
1264
                            // union/intersect types: try the next type, if not valid, an exception will be thrown at the end
UNCOV
1265
                            if ($isMultipleTypes) {
×
1266
                                break 2;
×
1267
                            }
UNCOV
1268
                            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);
×
1269
                        }
UNCOV
1270
                        break;
8✔
UNCOV
1271
                    case TypeIdentifier::FLOAT:
14✔
UNCOV
1272
                        if (is_numeric($value)) {
8✔
UNCOV
1273
                            return (float) $value;
2✔
1274
                        }
1275

1276
                        switch ($value) {
UNCOV
1277
                            case 'NaN':
6✔
UNCOV
1278
                                return \NAN;
2✔
UNCOV
1279
                            case 'INF':
4✔
UNCOV
1280
                                return \INF;
2✔
UNCOV
1281
                            case '-INF':
2✔
UNCOV
1282
                                return -\INF;
2✔
1283
                            default:
1284
                                // union/intersect types: try the next type, if not valid, an exception will be thrown at the end
UNCOV
1285
                                if ($isMultipleTypes) {
×
1286
                                    break 3;
×
1287
                                }
UNCOV
1288
                                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);
×
1289
                        }
1290
                }
1291
            }
1292

1293
            if ($context[static::DISABLE_TYPE_ENFORCEMENT] ?? false) {
342✔
UNCOV
1294
                return $value;
×
1295
            }
1296

1297
            try {
1298
                $t instanceof Type
342✔
1299
                    ? $this->validateAttributeType($attribute, $t, $value, $format, $context)
342✔
UNCOV
1300
                    : $this->validateType($attribute, $t, $value, $format, $context);
×
1301

1302
                $denormalizationException = null;
330✔
1303
                break;
330✔
1304
            } catch (NotNormalizableValueException $e) {
76✔
1305
                // union/intersect types: try the next type
1306
                if (!$isMultipleTypes) {
76✔
UNCOV
1307
                    throw $e;
7✔
1308
                }
1309

1310
                $denormalizationException ??= $e;
69✔
1311
            }
1312
        }
1313

1314
        if ($denormalizationException) {
343✔
1315
            if ($type instanceof Type && $type->isSatisfiedBy(static fn ($type) => $type instanceof BuiltinType) && !$type->isSatisfiedBy($typeIsResourceClass)) {
10✔
1316
                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);
6✔
1317
            }
1318

1319
            throw $denormalizationException;
6✔
1320
        }
1321

1322
        return $value;
338✔
1323
    }
1324

1325
    /**
1326
     * Sets a value of the object using the PropertyAccess component.
1327
     */
1328
    private function setValue(object $object, string $attributeName, mixed $value): void
1329
    {
1330
        try {
1331
            $this->propertyAccessor->setValue($object, $attributeName, $value);
372✔
UNCOV
1332
        } catch (NoSuchPropertyException) {
17✔
1333
            // Properties not found are ignored
1334
        }
1335
    }
1336
}
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