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

api-platform / core / 15955054194

29 Jun 2025 12:10PM UTC coverage: 22.026% (+0.2%) from 21.793%
15955054194

push

github

soyuka
cs: unused namespace

11500 of 52210 relevant lines covered (22.03%)

21.66 hits per line

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

56.81
/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\AccessDeniedException;
19
use ApiPlatform\Metadata\Exception\InvalidArgumentException;
20
use ApiPlatform\Metadata\Exception\ItemNotFoundException;
21
use ApiPlatform\Metadata\IriConverterInterface;
22
use ApiPlatform\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
23
use ApiPlatform\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
24
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
25
use ApiPlatform\Metadata\ResourceAccessCheckerInterface;
26
use ApiPlatform\Metadata\ResourceClassResolverInterface;
27
use ApiPlatform\Metadata\UrlGeneratorInterface;
28
use ApiPlatform\Metadata\Util\ClassInfoTrait;
29
use ApiPlatform\Metadata\Util\CloneTrait;
30
use Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException;
31
use Symfony\Component\PropertyAccess\PropertyAccess;
32
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
33
use Symfony\Component\PropertyInfo\PropertyInfoExtractor;
34
use Symfony\Component\PropertyInfo\Type as LegacyType;
35
use Symfony\Component\Serializer\Encoder\CsvEncoder;
36
use Symfony\Component\Serializer\Encoder\XmlEncoder;
37
use Symfony\Component\Serializer\Exception\LogicException;
38
use Symfony\Component\Serializer\Exception\MissingConstructorArgumentsException;
39
use Symfony\Component\Serializer\Exception\NotNormalizableValueException;
40
use Symfony\Component\Serializer\Exception\RuntimeException;
41
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
42
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
43
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
44
use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer;
45
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
46
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
47
use Symfony\Component\TypeInfo\Type;
48
use Symfony\Component\TypeInfo\Type\BuiltinType;
49
use Symfony\Component\TypeInfo\Type\CollectionType;
50
use Symfony\Component\TypeInfo\Type\CompositeTypeInterface;
51
use Symfony\Component\TypeInfo\Type\NullableType;
52
use Symfony\Component\TypeInfo\Type\ObjectType;
53
use Symfony\Component\TypeInfo\Type\WrappingTypeInterface;
54
use Symfony\Component\TypeInfo\TypeIdentifier;
55

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

176
            return $iri;
×
177
        }
178

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

183
        return $data;
448✔
184
    }
185

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

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

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

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

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

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

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

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

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

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

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

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

250
        if (!\is_array($data)) {
14✔
251
            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);
×
252
        }
253

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

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

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

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

270
        $operation = $context['operation'] ?? null;
12✔
271
        $throwOnAccessDenied = $operation?->getExtraProperties()['throw_on_access_denied'] ?? false;
12✔
272
        $securityMessage = $operation?->getSecurityMessage() ?? null;
12✔
273

274
        // Revert attributes that aren't allowed to be changed after a post-denormalize check
275
        foreach (array_keys($data) as $attribute) {
12✔
276
            $attribute = $this->nameConverter ? $this->nameConverter->denormalize((string) $attribute) : $attribute;
10✔
277
            $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $attribute, $options);
10✔
278
            $attributeExtraProperties = $propertyMetadata->getExtraProperties() ?? [];
10✔
279
            $throwOnPropertyAccessDenied = $attributeExtraProperties['throw_on_access_denied'] ?? $throwOnAccessDenied;
10✔
280
            if (!\in_array($attribute, $propertyNames, true)) {
10✔
281
                continue;
×
282
            }
283

284
            if (!$this->canAccessAttributePostDenormalize($object, $previousObject, $attribute, $context)) {
10✔
285
                if ($throwOnPropertyAccessDenied) {
×
286
                    throw new AccessDeniedException($securityMessage ?? 'Access denied');
×
287
                }
288
                if (null !== $previousObject) {
×
289
                    $this->setValue($object, $attribute, $this->propertyAccessor->getValue($previousObject, $attribute));
×
290
                } else {
291
                    $this->setValue($object, $attribute, $propertyMetadata->getDefault());
×
292
                }
293
            }
294
        }
295

296
        return $object;
12✔
297
    }
298

299
    /**
300
     * Method copy-pasted from symfony/serializer.
301
     * Remove it after symfony/serializer version update @see https://github.com/symfony/symfony/pull/28263.
302
     *
303
     * {@inheritdoc}
304
     *
305
     * @internal
306
     */
307
    protected function instantiateObject(array &$data, string $class, array &$context, \ReflectionClass $reflectionClass, array|bool $allowedAttributes, ?string $format = null): object
308
    {
309
        if (null !== $object = $this->extractObjectToPopulate($class, $context, static::OBJECT_TO_POPULATE)) {
14✔
310
            unset($context[static::OBJECT_TO_POPULATE]);
×
311

312
            return $object;
×
313
        }
314

315
        $class = $this->getClassDiscriminatorResolvedClass($data, $class, $context);
14✔
316
        $reflectionClass = new \ReflectionClass($class);
14✔
317

318
        $constructor = $this->getConstructor($data, $class, $context, $reflectionClass, $allowedAttributes);
14✔
319
        if ($constructor) {
14✔
320
            $constructorParameters = $constructor->getParameters();
12✔
321

322
            $params = [];
12✔
323
            $missingConstructorArguments = [];
12✔
324
            foreach ($constructorParameters as $constructorParameter) {
12✔
325
                $paramName = $constructorParameter->name;
8✔
326
                $key = $this->nameConverter ? $this->nameConverter->normalize($paramName, $class, $format, $context) : $paramName;
8✔
327
                $attributeContext = $this->getAttributeDenormalizationContext($class, $paramName, $context);
8✔
328
                $attributeContext['deserialization_path'] = $attributeContext['deserialization_path'] ?? $key;
8✔
329

330
                $allowed = false === $allowedAttributes || (\is_array($allowedAttributes) && \in_array($paramName, $allowedAttributes, true));
8✔
331
                $ignored = !$this->isAllowedAttribute($class, $paramName, $format, $context);
8✔
332
                if ($constructorParameter->isVariadic()) {
8✔
333
                    if ($allowed && !$ignored && (isset($data[$key]) || \array_key_exists($key, $data))) {
×
334
                        if (!\is_array($data[$paramName])) {
×
335
                            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));
×
336
                        }
337

338
                        $params[] = $data[$paramName];
×
339
                    }
340
                } elseif ($allowed && !$ignored && (isset($data[$key]) || \array_key_exists($key, $data))) {
8✔
341
                    try {
342
                        $params[] = $this->createConstructorArgument($data[$key], $key, $constructorParameter, $attributeContext, $format);
2✔
343
                    } catch (NotNormalizableValueException $exception) {
2✔
344
                        if (!isset($context['not_normalizable_value_exceptions'])) {
2✔
345
                            throw $exception;
×
346
                        }
347
                        $context['not_normalizable_value_exceptions'][] = $exception;
2✔
348
                    }
349

350
                    // Don't run set for a parameter passed to the constructor
351
                    unset($data[$key]);
2✔
352
                } elseif (isset($context[static::DEFAULT_CONSTRUCTOR_ARGUMENTS][$class][$key])) {
8✔
353
                    $params[] = $context[static::DEFAULT_CONSTRUCTOR_ARGUMENTS][$class][$key];
×
354
                } elseif ($constructorParameter->isDefaultValueAvailable()) {
8✔
355
                    $params[] = $constructorParameter->getDefaultValue();
6✔
356
                } else {
357
                    if (!isset($context['not_normalizable_value_exceptions'])) {
2✔
358
                        $missingConstructorArguments[] = $constructorParameter->name;
×
359
                    }
360

361
                    $constructorParameterType = 'unknown';
2✔
362
                    $reflectionType = $constructorParameter->getType();
2✔
363
                    if ($reflectionType instanceof \ReflectionNamedType) {
2✔
364
                        $constructorParameterType = $reflectionType->getName();
2✔
365
                    }
366

367
                    $exception = NotNormalizableValueException::createForUnexpectedDataType(
2✔
368
                        \sprintf('Failed to create object because the class misses the "%s" property.', $constructorParameter->name),
2✔
369
                        null,
2✔
370
                        [$constructorParameterType],
2✔
371
                        $attributeContext['deserialization_path'],
2✔
372
                        true
2✔
373
                    );
2✔
374
                    $context['not_normalizable_value_exceptions'][] = $exception;
2✔
375
                }
376
            }
377

378
            if ($missingConstructorArguments) {
12✔
379
                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);
×
380
            }
381

382
            if (\count($context['not_normalizable_value_exceptions'] ?? []) > 0) {
12✔
383
                return $reflectionClass->newInstanceWithoutConstructor();
2✔
384
            }
385

386
            if ($constructor->isConstructor()) {
10✔
387
                return $reflectionClass->newInstanceArgs($params);
10✔
388
            }
389

390
            return $constructor->invokeArgs(null, $params);
×
391
        }
392

393
        return new $class();
2✔
394
    }
395

396
    protected function getClassDiscriminatorResolvedClass(array $data, string $class, array $context = []): string
397
    {
398
        if (null === $this->classDiscriminatorResolver || (null === $mapping = $this->classDiscriminatorResolver->getMappingForClass($class))) {
16✔
399
            return $class;
16✔
400
        }
401

402
        if (!isset($data[$mapping->getTypeProperty()])) {
×
403
            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());
×
404
        }
405

406
        $type = $data[$mapping->getTypeProperty()];
×
407
        if (null === ($mappedClass = $mapping->getClassForType($type))) {
×
408
            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);
×
409
        }
410

411
        return $mappedClass;
×
412
    }
413

414
    protected function createConstructorArgument($parameterData, string $key, \ReflectionParameter $constructorParameter, array $context, ?string $format = null): mixed
415
    {
416
        return $this->createAndValidateAttributeValue($constructorParameter->name, $parameterData, $format, $context);
2✔
417
    }
418

419
    /**
420
     * {@inheritdoc}
421
     *
422
     * Unused in this context.
423
     *
424
     * @return string[]
425
     */
426
    protected function extractAttributes($object, $format = null, array $context = []): array
427
    {
428
        return [];
×
429
    }
430

431
    /**
432
     * {@inheritdoc}
433
     */
434
    protected function getAllowedAttributes(string|object $classOrObject, array $context, bool $attributesAsString = false): array|bool
435
    {
436
        if (!$this->resourceClassResolver->isResourceClass($context['resource_class'])) {
448✔
437
            return parent::getAllowedAttributes($classOrObject, $context, $attributesAsString);
12✔
438
        }
439

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

444
        $allowedAttributes = [];
436✔
445
        foreach ($propertyNames as $propertyName) {
436✔
446
            $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $propertyName, $options);
428✔
447

448
            if (
449
                $this->isAllowedAttribute($classOrObject, $propertyName, null, $context)
428✔
450
                && (isset($context['api_normalize']) && $propertyMetadata->isReadable()
428✔
451
                    || isset($context['api_denormalize']) && ($propertyMetadata->isWritable() || !\is_object($classOrObject) && $propertyMetadata->isInitializable())
428✔
452
                )
453
            ) {
454
                $allowedAttributes[] = $propertyName;
422✔
455
            }
456
        }
457

458
        return $allowedAttributes;
436✔
459
    }
460

461
    /**
462
     * {@inheritdoc}
463
     */
464
    protected function isAllowedAttribute(object|string $classOrObject, string $attribute, ?string $format = null, array $context = []): bool
465
    {
466
        if (!parent::isAllowedAttribute($classOrObject, $attribute, $format, $context)) {
440✔
467
            return false;
16✔
468
        }
469

470
        return $this->canAccessAttribute(\is_object($classOrObject) ? $classOrObject : null, $attribute, $context);
440✔
471
    }
472

473
    /**
474
     * Check if access to the attribute is granted.
475
     */
476
    protected function canAccessAttribute(?object $object, string $attribute, array $context = []): bool
477
    {
478
        if (!$this->resourceClassResolver->isResourceClass($context['resource_class'])) {
440✔
479
            return true;
12✔
480
        }
481

482
        $options = $this->getFactoryOptions($context);
428✔
483
        $propertyMetadata = $this->propertyMetadataFactory->create($context['resource_class'], $attribute, $options);
428✔
484
        $security = $propertyMetadata->getSecurity() ?? $propertyMetadata->getPolicy();
428✔
485
        if (null !== $this->resourceAccessChecker && $security) {
428✔
486
            return $this->resourceAccessChecker->isGranted($context['resource_class'], $security, [
2✔
487
                'object' => $object,
2✔
488
                'property' => $attribute,
2✔
489
            ]);
2✔
490
        }
491

492
        return true;
428✔
493
    }
494

495
    /**
496
     * Check if access to the attribute is granted.
497
     */
498
    protected function canAccessAttributePostDenormalize(?object $object, ?object $previousObject, string $attribute, array $context = []): bool
499
    {
500
        $options = $this->getFactoryOptions($context);
10✔
501
        $propertyMetadata = $this->propertyMetadataFactory->create($context['resource_class'], $attribute, $options);
10✔
502
        $security = $propertyMetadata->getSecurityPostDenormalize();
10✔
503
        if ($this->resourceAccessChecker && $security) {
10✔
504
            return $this->resourceAccessChecker->isGranted($context['resource_class'], $security, [
×
505
                'object' => $object,
×
506
                'previous_object' => $previousObject,
×
507
                'property' => $attribute,
×
508
            ]);
×
509
        }
510

511
        return true;
10✔
512
    }
513

514
    /**
515
     * {@inheritdoc}
516
     */
517
    protected function setAttributeValue(object $object, string $attribute, mixed $value, ?string $format = null, array $context = []): void
518
    {
519
        try {
520
            $this->setValue($object, $attribute, $this->createAttributeValue($attribute, $value, $format, $context));
12✔
521
        } catch (NotNormalizableValueException $exception) {
4✔
522
            // Only throw if collecting denormalization errors is disabled.
523
            if (!isset($context['not_normalizable_value_exceptions'])) {
2✔
524
                throw $exception;
×
525
            }
526
        }
527
    }
528

529
    /**
530
     * @deprecated since 4.1, use "validateAttributeType" instead
531
     *
532
     * Validates the type of the value. Allows using integers as floats for JSON formats.
533
     *
534
     * @throws NotNormalizableValueException
535
     */
536
    protected function validateType(string $attribute, LegacyType $type, mixed $value, ?string $format = null, array $context = []): void
537
    {
538
        trigger_deprecation('api-platform/serializer', '4.1', 'The "%s()" method is deprecated, use "%s::validateAttributeType()" instead.', __METHOD__, self::class);
×
539

540
        $builtinType = $type->getBuiltinType();
×
541
        if (LegacyType::BUILTIN_TYPE_FLOAT === $builtinType && null !== $format && str_contains($format, 'json')) {
×
542
            $isValid = \is_float($value) || \is_int($value);
×
543
        } else {
544
            $isValid = \call_user_func('is_'.$builtinType, $value);
×
545
        }
546

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

552
    /**
553
     * Validates the type of the value. Allows using integers as floats for JSON formats.
554
     *
555
     * @throws NotNormalizableValueException
556
     */
557
    protected function validateAttributeType(string $attribute, Type $type, mixed $value, ?string $format = null, array $context = []): void
558
    {
559
        if ($type->isIdentifiedBy(TypeIdentifier::FLOAT) && null !== $format && str_contains($format, 'json')) {
8✔
560
            $isValid = \is_float($value) || \is_int($value);
×
561
        } else {
562
            $isValid = $type->accepts($value);
8✔
563
        }
564

565
        if (!$isValid) {
8✔
566
            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✔
567
        }
568
    }
569

570
    /**
571
     * @deprecated since 4.1, use "denormalizeObjectCollection" instead.
572
     *
573
     * Denormalizes a collection of objects.
574
     *
575
     * @throws NotNormalizableValueException
576
     */
577
    protected function denormalizeCollection(string $attribute, ApiProperty $propertyMetadata, LegacyType $type, string $className, mixed $value, ?string $format, array $context): array
578
    {
579
        trigger_deprecation('api-platform/serializer', '4.1', 'The "%s()" method is deprecated, use "%s::denormalizeObjectCollection()" instead.', __METHOD__, self::class);
×
580

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

585
        $values = [];
×
586
        $childContext = $this->createChildContext($this->createOperationContext($context, $className), $attribute, $format);
×
587
        $collectionKeyTypes = $type->getCollectionKeyTypes();
×
588
        foreach ($value as $index => $obj) {
×
589
            $currentChildContext = $childContext;
×
590
            if (isset($childContext['deserialization_path'])) {
×
591
                $currentChildContext['deserialization_path'] = "{$childContext['deserialization_path']}[{$index}]";
×
592
            }
593

594
            // no typehint provided on collection key
595
            if (!$collectionKeyTypes) {
×
596
                $values[$index] = $this->denormalizeRelation($attribute, $propertyMetadata, $className, $obj, $format, $currentChildContext);
×
597
                continue;
×
598
            }
599

600
            // validate collection key typehint
601
            foreach ($collectionKeyTypes as $collectionKeyType) {
×
602
                $collectionKeyBuiltinType = $collectionKeyType->getBuiltinType();
×
603
                if (!\call_user_func('is_'.$collectionKeyBuiltinType, $index)) {
×
604
                    continue;
×
605
                }
606

607
                $values[$index] = $this->denormalizeRelation($attribute, $propertyMetadata, $className, $obj, $format, $currentChildContext);
×
608
                continue 2;
×
609
            }
610
            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);
×
611
        }
612

613
        return $values;
×
614
    }
615

616
    /**
617
     * Denormalizes a collection of objects.
618
     *
619
     * @throws NotNormalizableValueException
620
     */
621
    protected function denormalizeObjectCollection(string $attribute, ApiProperty $propertyMetadata, Type $type, string $className, mixed $value, ?string $format, array $context): array
622
    {
623
        if (!\is_array($value)) {
2✔
624
            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✔
625
        }
626

627
        $values = [];
×
628
        $childContext = $this->createChildContext($this->createOperationContext($context, $className), $attribute, $format);
×
629

630
        foreach ($value as $index => $obj) {
×
631
            $currentChildContext = $childContext;
×
632
            if (isset($childContext['deserialization_path'])) {
×
633
                $currentChildContext['deserialization_path'] = "{$childContext['deserialization_path']}[{$index}]";
×
634
            }
635

636
            if ($type instanceof CollectionType) {
×
637
                $collectionKeyType = $type->getCollectionKeyType();
×
638

639
                while ($collectionKeyType instanceof WrappingTypeInterface) {
×
640
                    $collectionKeyType = $type->getWrappedType();
×
641
                }
642

643
                if (!$collectionKeyType->accepts($index)) {
×
644
                    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);
×
645
                }
646
            }
647

648
            $values[$index] = $this->denormalizeRelation($attribute, $propertyMetadata, $className, $obj, $format, $currentChildContext);
×
649
        }
650

651
        return $values;
×
652
    }
653

654
    /**
655
     * Denormalizes a relation.
656
     *
657
     * @throws LogicException
658
     * @throws UnexpectedValueException
659
     * @throws NotNormalizableValueException
660
     */
661
    protected function denormalizeRelation(string $attributeName, ApiProperty $propertyMetadata, string $className, mixed $value, ?string $format, array $context): ?object
662
    {
663
        if (\is_string($value)) {
6✔
664
            try {
665
                return $this->iriConverter->getResourceFromIri($value, $context + ['fetch_data' => true]);
4✔
666
            } catch (ItemNotFoundException $e) {
2✔
667
                if (!isset($context['not_normalizable_value_exceptions'])) {
×
668
                    throw new UnexpectedValueException($e->getMessage(), $e->getCode(), $e);
×
669
                }
670

671
                throw NotNormalizableValueException::createForUnexpectedDataType($e->getMessage(), $value, [$className], $context['deserialization_path'] ?? null, true, $e->getCode(), $e);
×
672
            } catch (InvalidArgumentException $e) {
2✔
673
                if (!isset($context['not_normalizable_value_exceptions'])) {
×
674
                    throw new UnexpectedValueException(\sprintf('Invalid IRI "%s".', $value), $e->getCode(), $e);
×
675
                }
676

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

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

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

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

693
            return $item;
×
694
        }
695

696
        if (!\is_array($value)) {
2✔
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);
×
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 = [];
448✔
709
        if (isset($context[self::GROUPS])) {
448✔
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];
158✔
712
        }
713

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

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

730
        return $options + $this->localFactoryOptionsCache[$operationCacheKey.$suffix] = $options;
448✔
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;
434✔
741
        $context['property_metadata'] = $propertyMetadata = $this->propertyMetadataFactory->create($context['resource_class'], $attribute, $this->getFactoryOptions($context));
434✔
742

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

747
        if (!method_exists(PropertyInfoExtractor::class, 'getType')) {
434✔
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, $propertyMetadata), $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, $propertyMetadata), $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, $propertyMetadata), $attribute, $format);
×
837
                    $attributeValue = $this->propertyAccessor->getValue($object, $attribute);
×
838

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

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

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

850
                    $attributeValue = $this->propertyAccessor->getValue($object, $attribute);
×
851

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

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

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

866
            $attributeValue = $this->propertyAccessor->getValue($object, $attribute);
×
867

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

871
        $type = $propertyMetadata->getNativeType();
434✔
872

873
        $nullable = false;
434✔
874
        if ($type instanceof NullableType) {
434✔
875
            $type = $type->getWrappedType();
278✔
876
            $nullable = true;
278✔
877
        }
878

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

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

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

899
                    return $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_PATH, $operation, $childContext);
×
900
                }
901

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

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

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

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

914
                if ($this->tagCollector) {
14✔
915
                    $this->tagCollector->collect($context);
14✔
916
                }
917

918
                return $data;
14✔
919
            }
920

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

930
                    return $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_PATH, $operation, $childContext);
×
931
                }
932

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

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

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

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

945
                if ($this->tagCollector) {
20✔
946
                    $this->tagCollector->collect($context);
12✔
947
                }
948

949
                return $data;
20✔
950
            }
951

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

956
            unset(
432✔
957
                $context['resource_class'],
432✔
958
                $context['force_resource_class'],
432✔
959
                $context['uri_variables'],
432✔
960
            );
432✔
961

962
            // Anonymous resources
963
            if ($className) {
432✔
964
                $childContext = $this->createChildContext($this->createOperationContext($context, $className, $propertyMetadata), $attribute, $format);
160✔
965
                $attributeValue = $this->propertyAccessor->getValue($object, $attribute);
160✔
966

967
                return $this->serializer->normalize($attributeValue, $format, $childContext);
160✔
968
            }
969

970
            if ($type instanceof CollectionType) {
426✔
971
                if (($subType = $type->getCollectionValueType()) instanceof ObjectType) {
52✔
972
                    $context = $this->createOperationContext($context, $subType->getClassName(), $propertyMetadata);
×
973
                }
974

975
                $childContext = $this->createChildContext($context, $attribute, $format);
52✔
976
                $attributeValue = $this->propertyAccessor->getValue($object, $attribute);
52✔
977

978
                return $this->serializer->normalize($attributeValue, $format, $childContext);
52✔
979
            }
980
        }
981

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

986
        unset(
428✔
987
            $context['resource_class'],
428✔
988
            $context['force_resource_class'],
428✔
989
            $context['uri_variables']
428✔
990
        );
428✔
991

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

994
        return $this->serializer->normalize($attributeValue, $format, $context);
426✔
995
    }
996

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

1010
            // update context, if concrete object class deviates from general relation class (e.g. in case of polymorphic resources)
1011
            $objResourceClass = $this->resourceClassResolver->getResourceClass($obj, $resourceClass);
2✔
1012
            $context['resource_class'] = $objResourceClass;
2✔
1013
            if ($this->resourceMetadataCollectionFactory) {
2✔
1014
                $context['operation'] = $this->resourceMetadataCollectionFactory->create($objResourceClass)->getOperation();
2✔
1015
            }
1016

1017
            $value[$index] = $this->normalizeRelation($propertyMetadata, $obj, $resourceClass, $format, $context);
2✔
1018
        }
1019

1020
        return $value;
14✔
1021
    }
1022

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

1036
            $relatedContext = $this->createOperationContext($context, $resourceClass, $propertyMetadata);
14✔
1037
            $normalizedRelatedObject = $this->serializer->normalize($relatedObject, $format, $relatedContext);
14✔
1038
            if (!\is_string($normalizedRelatedObject) && !\is_array($normalizedRelatedObject) && !$normalizedRelatedObject instanceof \ArrayObject && null !== $normalizedRelatedObject) {
14✔
1039
                throw new UnexpectedValueException('Expected normalized relation to be an IRI, array, \ArrayObject or null');
×
1040
            }
1041

1042
            return $normalizedRelatedObject;
14✔
1043
        }
1044

1045
        $context['iri'] = $iri = $this->iriConverter->getIriFromResource(resource: $relatedObject, context: $context);
8✔
1046
        $context['data'] = $iri;
8✔
1047
        $context['object'] = $relatedObject;
8✔
1048
        unset($context['property_metadata'], $context['api_attribute']);
8✔
1049

1050
        if ($this->tagCollector) {
8✔
1051
            $this->tagCollector->collect($context);
4✔
1052
        } elseif (isset($context['resources'])) {
4✔
1053
            $context['resources'][$iri] = $iri;
×
1054
        }
1055

1056
        $push = $propertyMetadata->getPush() ?? false;
8✔
1057
        if (isset($context['resources_to_push']) && $push) {
8✔
1058
            $context['resources_to_push'][$iri] = $iri;
×
1059
        }
1060

1061
        return $iri;
8✔
1062
    }
1063

1064
    private function createAttributeValue(string $attribute, mixed $value, ?string $format = null, array &$context = []): mixed
1065
    {
1066
        try {
1067
            return $this->createAndValidateAttributeValue($attribute, $value, $format, $context);
12✔
1068
        } catch (NotNormalizableValueException $exception) {
4✔
1069
            if (!isset($context['not_normalizable_value_exceptions'])) {
2✔
1070
                throw $exception;
×
1071
            }
1072
            $context['not_normalizable_value_exceptions'][] = $exception;
2✔
1073
            throw $exception;
2✔
1074
        }
1075
    }
1076

1077
    private function createAndValidateAttributeValue(string $attribute, mixed $value, ?string $format = null, array $context = []): mixed
1078
    {
1079
        $propertyMetadata = $this->propertyMetadataFactory->create($context['resource_class'], $attribute, $this->getFactoryOptions($context));
12✔
1080
        $denormalizationException = null;
12✔
1081

1082
        $types = [];
12✔
1083
        $type = null;
12✔
1084
        if (!method_exists(PropertyInfoExtractor::class, 'getType')) {
12✔
1085
            $types = $propertyMetadata->getBuiltinTypes() ?? [];
×
1086
        } else {
1087
            $type = $propertyMetadata->getNativeType();
12✔
1088
            $types = $type instanceof CompositeTypeInterface ? $type->getTypes() : (null === $type ? [] : [$type]);
12✔
1089
        }
1090

1091
        $isMultipleTypes = \count($types) > 1;
12✔
1092
        $className = null;
12✔
1093
        $typeIsResourceClass = function (Type $type) use (&$className): bool {
12✔
1094
            return $type instanceof ObjectType ? $this->resourceClassResolver->isResourceClass($className = $type->getClassName()) : false;
12✔
1095
        };
12✔
1096

1097
        $isMultipleTypes = \count($types) > 1;
12✔
1098
        $denormalizationException = null;
12✔
1099

1100
        foreach ($types as $t) {
12✔
1101
            if ($type instanceof Type) {
12✔
1102
                $isNullable = $type->isNullable();
12✔
1103
            } else {
1104
                $isNullable = $t->isNullable();
×
1105
            }
1106

1107
            if (null === $value && ($isNullable || ($context[static::DISABLE_TYPE_ENFORCEMENT] ?? false))) {
12✔
1108
                return $value;
×
1109
            }
1110

1111
            $collectionValueType = null;
12✔
1112

1113
            if ($t instanceof CollectionType) {
12✔
1114
                $collectionValueType = $t->getCollectionValueType();
2✔
1115
            } elseif ($t instanceof LegacyType) {
12✔
1116
                $collectionValueType = $t->getCollectionValueTypes()[0] ?? null;
×
1117
            }
1118

1119
            /* From @see AbstractObjectNormalizer::validateAndDenormalize() */
1120
            // Fix a collection that contains the only one element
1121
            // This is special to xml format only
1122
            if ('xml' === $format && null !== $collectionValueType && (!\is_array($value) || !\is_int(key($value)))) {
12✔
1123
                $isMixedType = $collectionValueType instanceof Type && $collectionValueType->isIdentifiedBy(TypeIdentifier::MIXED);
×
1124
                if (!$isMixedType) {
×
1125
                    $value = [$value];
×
1126
                }
1127
            }
1128

1129
            if (($collectionValueType instanceof Type && $collectionValueType->isSatisfiedBy($typeIsResourceClass))
12✔
1130
                || ($t instanceof LegacyType && $t->isCollection() && null !== $collectionValueType && null !== ($className = $collectionValueType->getClassName()) && $this->resourceClassResolver->isResourceClass($className))
12✔
1131
            ) {
1132
                $resourceClass = $this->resourceClassResolver->getResourceClass(null, $className);
2✔
1133
                $context['resource_class'] = $resourceClass;
2✔
1134
                unset($context['uri_variables']);
2✔
1135

1136
                try {
1137
                    return $t instanceof Type
2✔
1138
                        ? $this->denormalizeObjectCollection($attribute, $propertyMetadata, $t, $resourceClass, $value, $format, $context)
2✔
1139
                        : $this->denormalizeCollection($attribute, $propertyMetadata, $t, $resourceClass, $value, $format, $context);
×
1140
                } catch (NotNormalizableValueException $e) {
2✔
1141
                    // union/intersect types: try the next type, if not valid, an exception will be thrown at the end
1142
                    if ($isMultipleTypes) {
2✔
1143
                        $denormalizationException ??= $e;
×
1144

1145
                        continue;
×
1146
                    }
1147

1148
                    throw $e;
2✔
1149
                }
1150
            }
1151

1152
            if (
1153
                ($t instanceof Type && $t->isSatisfiedBy($typeIsResourceClass))
12✔
1154
                || ($t instanceof LegacyType && null !== ($className = $t->getClassName()) && $this->resourceClassResolver->isResourceClass($className))
12✔
1155
            ) {
1156
                $resourceClass = $this->resourceClassResolver->getResourceClass(null, $className);
6✔
1157
                $childContext = $this->createChildContext($this->createOperationContext($context, $resourceClass, $propertyMetadata), $attribute, $format);
6✔
1158

1159
                try {
1160
                    return $this->denormalizeRelation($attribute, $propertyMetadata, $resourceClass, $value, $format, $childContext);
6✔
1161
                } catch (NotNormalizableValueException $e) {
4✔
1162
                    // union/intersect types: try the next type, if not valid, an exception will be thrown at the end
1163
                    if ($isMultipleTypes) {
2✔
1164
                        $denormalizationException ??= $e;
2✔
1165

1166
                        continue;
2✔
1167
                    }
1168

1169
                    throw $e;
×
1170
                }
1171
            }
1172

1173
            if (
1174
                ($t instanceof CollectionType && $collectionValueType instanceof ObjectType)
8✔
1175
                || ($t instanceof LegacyType && $t->isCollection() && null !== $collectionValueType && null !== $collectionValueType->getClassName())
8✔
1176
            ) {
1177
                $className = $collectionValueType->getClassName();
×
1178
                if (!$this->serializer instanceof DenormalizerInterface) {
×
1179
                    throw new LogicException(\sprintf('The injected serializer must be an instance of "%s".', DenormalizerInterface::class));
×
1180
                }
1181

1182
                unset($context['resource_class'], $context['uri_variables']);
×
1183

1184
                try {
1185
                    return $this->serializer->denormalize($value, $className.'[]', $format, $context);
×
1186
                } catch (NotNormalizableValueException $e) {
×
1187
                    // union/intersect types: try the next type, if not valid, an exception will be thrown at the end
1188
                    if ($isMultipleTypes) {
×
1189
                        $denormalizationException ??= $e;
×
1190

1191
                        continue;
×
1192
                    }
1193

1194
                    throw $e;
×
1195
                }
1196
            }
1197

1198
            while ($t instanceof WrappingTypeInterface) {
8✔
1199
                $t = $t->getWrappedType();
×
1200
            }
1201

1202
            if (
1203
                $t instanceof ObjectType
8✔
1204
                || ($t instanceof LegacyType && null !== $t->getClassName())
8✔
1205
            ) {
1206
                if (!$this->serializer instanceof DenormalizerInterface) {
2✔
1207
                    throw new LogicException(\sprintf('The injected serializer must be an instance of "%s".', DenormalizerInterface::class));
×
1208
                }
1209

1210
                unset($context['resource_class'], $context['uri_variables']);
2✔
1211

1212
                try {
1213
                    return $this->serializer->denormalize($value, $t->getClassName(), $format, $context);
2✔
1214
                } catch (NotNormalizableValueException $e) {
2✔
1215
                    // union/intersect types: try the next type, if not valid, an exception will be thrown at the end
1216
                    if ($isMultipleTypes) {
2✔
1217
                        $denormalizationException ??= $e;
2✔
1218

1219
                        continue;
2✔
1220
                    }
1221

1222
                    throw $e;
×
1223
                }
1224
            }
1225

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

1238
                $typeIdentifier = $t instanceof BuiltinType ? $t->getTypeIdentifier() : TypeIdentifier::tryFrom($t->getBuiltinType());
×
1239

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

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

1288
            if ($context[static::DISABLE_TYPE_ENFORCEMENT] ?? false) {
8✔
1289
                return $value;
×
1290
            }
1291

1292
            try {
1293
                $t instanceof Type
8✔
1294
                    ? $this->validateAttributeType($attribute, $t, $value, $format, $context)
8✔
1295
                    : $this->validateType($attribute, $t, $value, $format, $context);
×
1296

1297
                $denormalizationException = null;
6✔
1298
                break;
6✔
1299
            } catch (NotNormalizableValueException $e) {
2✔
1300
                // union/intersect types: try the next type
1301
                if (!$isMultipleTypes) {
2✔
1302
                    throw $e;
×
1303
                }
1304

1305
                $denormalizationException ??= $e;
2✔
1306
            }
1307
        }
1308

1309
        if ($denormalizationException) {
8✔
1310
            if ($type instanceof Type && $type->isSatisfiedBy(static fn ($type) => $type instanceof BuiltinType) && !$type->isSatisfiedBy($typeIsResourceClass)) {
2✔
1311
                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✔
1312
            }
1313

1314
            throw $denormalizationException;
2✔
1315
        }
1316

1317
        return $value;
6✔
1318
    }
1319

1320
    /**
1321
     * Sets a value of the object using the PropertyAccess component.
1322
     */
1323
    private function setValue(object $object, string $attributeName, mixed $value): void
1324
    {
1325
        try {
1326
            $this->propertyAccessor->setValue($object, $attributeName, $value);
8✔
1327
        } catch (NoSuchPropertyException) {
×
1328
            // Properties not found are ignored
1329
        }
1330
    }
1331
}
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