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

api-platform / core / 15779209812

20 Jun 2025 12:43PM UTC coverage: 22.065%. Remained the same
15779209812

Pull #7237

github

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

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

125 existing lines in 11 files now uncovered.

11487 of 52059 relevant lines covered (22.07%)

21.72 hits per line

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

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

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

12
declare(strict_types=1);
13

14
namespace ApiPlatform\Serializer;
15

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

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

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

73
    public function __construct(protected PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, protected PropertyMetadataFactoryInterface $propertyMetadataFactory, protected IriConverterInterface $iriConverter, protected ResourceClassResolverInterface $resourceClassResolver, ?PropertyAccessorInterface $propertyAccessor = null, ?NameConverterInterface $nameConverter = null, ?ClassMetadataFactoryInterface $classMetadataFactory = null, array $defaultContext = [], ?ResourceMetadataCollectionFactoryInterface $resourceMetadataCollectionFactory = null, ?ResourceAccessCheckerInterface $resourceAccessChecker = null, protected ?TagCollectorInterface $tagCollector = null)
74
    {
75
        if (!isset($defaultContext['circular_reference_handler'])) {
526✔
76
            $defaultContext['circular_reference_handler'] = fn ($object): ?string => $this->iriConverter->getIriFromResource($object);
514✔
77
        }
78

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

175
            return $iri;
×
176
        }
177

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

182
        return $data;
448✔
183
    }
184

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

286
        return $object;
12✔
287
    }
288

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

302
            return $object;
×
303
        }
304

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

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

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

320
                $allowed = false === $allowedAttributes || (\is_array($allowedAttributes) && \in_array($paramName, $allowedAttributes, true));
8✔
321
                $ignored = !$this->isAllowedAttribute($class, $paramName, $format, $context);
8✔
322
                if ($constructorParameter->isVariadic()) {
8✔
323
                    if ($allowed && !$ignored && (isset($data[$key]) || \array_key_exists($key, $data))) {
×
324
                        if (!\is_array($data[$paramName])) {
×
325
                            throw new RuntimeException(\sprintf('Cannot create an instance of %s from serialized data because the variadic parameter %s can only accept an array.', $class, $constructorParameter->name));
×
326
                        }
327

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

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

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

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

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

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

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

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

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

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

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

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

401
        return $mappedClass;
×
402
    }
403

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

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

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

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

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

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

448
        return $allowedAttributes;
436✔
449
    }
450

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

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

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

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

482
        return true;
428✔
483
    }
484

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

501
        return true;
10✔
502
    }
503

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

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

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

537
        if (!$isValid) {
×
538
            throw NotNormalizableValueException::createForUnexpectedDataType(\sprintf('The type of the "%s" attribute must be "%s", "%s" given.', $attribute, $builtinType, \gettype($value)), $value, [$builtinType], $context['deserialization_path'] ?? null);
×
539
        }
540
    }
541

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

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

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

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

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

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

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

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

603
        return $values;
×
604
    }
605

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

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

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

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

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

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

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

641
        return $values;
×
642
    }
643

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

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

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

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

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

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

683
            return $item;
×
684
        }
685

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

777
                    return $data;
×
778
                }
779

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

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

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

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

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

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

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

811
                    return $data;
×
812
                }
813

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

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

824
                // Anonymous resources
825
                if ($className) {
×
NEW
826
                    $childContext = $this->createChildContext($this->createOperationContext($context, $className, $propertyMetadata), $attribute, $format);
×
827
                    $attributeValue = $this->propertyAccessor->getValue($object, $attribute);
×
828

829
                    return $this->serializer->normalize($attributeValue, $format, $childContext);
×
830
                }
831

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

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

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

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

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

850
            unset(
×
851
                $context['resource_class'],
×
852
                $context['force_resource_class'],
×
853
                $context['uri_variables']
×
854
            );
×
855

856
            $attributeValue = $this->propertyAccessor->getValue($object, $attribute);
×
857

858
            return $this->serializer->normalize($attributeValue, $format, $context);
×
859
        }
860

861
        $type = $propertyMetadata->getNativeType();
434✔
862

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

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

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

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

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

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

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

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

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

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

908
                return $data;
14✔
909
            }
910

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

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

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

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

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

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

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

939
                return $data;
20✔
940
            }
941

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1010
        return $value;
14✔
1011
    }
1012

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

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

1032
            return $normalizedRelatedObject;
14✔
1033
        }
1034

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

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

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

1051
        return $iri;
8✔
1052
    }
1053

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

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

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

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

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

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

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

1101
            $collectionValueType = null;
12✔
1102

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

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

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

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

1135
                        continue;
×
1136
                    }
1137

1138
                    throw $e;
2✔
1139
                }
1140
            }
1141

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

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

1156
                        continue;
2✔
1157
                    }
1158

1159
                    throw $e;
×
1160
                }
1161
            }
1162

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

1171
                unset($context['resource_class'], $context['uri_variables']);
×
1172

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

1180
                        continue;
×
1181
                    }
1182

1183
                    throw $e;
×
1184
                }
1185
            }
1186

1187
            while ($t instanceof WrappingTypeInterface) {
8✔
1188
                $t = $t->getWrappedType();
×
1189
            }
1190

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

1199
                unset($context['resource_class'], $context['uri_variables']);
2✔
1200

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

1208
                        continue;
2✔
1209
                    }
1210

1211
                    throw $e;
×
1212
                }
1213
            }
1214

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

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

1229
                switch ($typeIdentifier) {
1230
                    case TypeIdentifier::BOOL:
×
1231
                        // according to http://www.w3.org/TR/xmlschema-2/#boolean, valid representations are "false", "true", "0" and "1"
1232
                        if ('false' === $value || '0' === $value) {
×
1233
                            $value = false;
×
1234
                        } elseif ('true' === $value || '1' === $value) {
×
1235
                            $value = true;
×
1236
                        } else {
1237
                            // union/intersect types: try the next type, if not valid, an exception will be thrown at the end
1238
                            if ($isMultipleTypes) {
×
1239
                                break 2;
×
1240
                            }
1241
                            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);
×
1242
                        }
1243
                        break;
×
1244
                    case TypeIdentifier::INT:
×
1245
                        if (ctype_digit($value) || ('-' === $value[0] && ctype_digit(substr($value, 1)))) {
×
1246
                            $value = (int) $value;
×
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 int ("%s" given).', $attribute, $className, $value), $value, ['int'], $context['deserialization_path'] ?? null);
×
1253
                        }
1254
                        break;
×
1255
                    case TypeIdentifier::FLOAT:
×
1256
                        if (is_numeric($value)) {
×
1257
                            return (float) $value;
×
1258
                        }
1259

1260
                        switch ($value) {
1261
                            case 'NaN':
×
1262
                                return \NAN;
×
1263
                            case 'INF':
×
1264
                                return \INF;
×
1265
                            case '-INF':
×
1266
                                return -\INF;
×
1267
                            default:
1268
                                // union/intersect types: try the next type, if not valid, an exception will be thrown at the end
1269
                                if ($isMultipleTypes) {
×
1270
                                    break 3;
×
1271
                                }
1272
                                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);
×
1273
                        }
1274
                }
1275
            }
1276

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

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

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

1294
                $denormalizationException ??= $e;
2✔
1295
            }
1296
        }
1297

1298
        if ($denormalizationException) {
8✔
1299
            if ($type instanceof Type && $type->isSatisfiedBy(static fn ($type) => $type instanceof BuiltinType) && !$type->isSatisfiedBy($typeIsResourceClass)) {
2✔
1300
                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✔
1301
            }
1302

1303
            throw $denormalizationException;
2✔
1304
        }
1305

1306
        return $value;
6✔
1307
    }
1308

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