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

api-platform / core / 5650127293

pending completion
5650127293

push

github

web-flow
fix: don't implement deprecated CacheableSupportsMethodInterface with Symfony 6.3+ (#5696)

* fix: don't implement deprecated CacheableSupportsMethodInterface

* fix: a check, and add tests

* fix ApiGatewayNormalizerTest

* more fixes

* fix more tests

* fix lowest

* only trigger the deprecation for Symfony 6.3

167 of 167 new or added lines in 23 files covered. (100.0%)

10865 of 18368 relevant lines covered (59.15%)

19.9 hits per line

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

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

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

59
    protected PropertyAccessorInterface $propertyAccessor;
60
    protected array $localCache = [];
61
    protected array $localFactoryOptionsCache = [];
62

63
    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, protected ?ResourceAccessCheckerInterface $resourceAccessChecker = null)
64
    {
65
        if (!isset($defaultContext['circular_reference_handler'])) {
152✔
66
            $defaultContext['circular_reference_handler'] = fn ($object): ?string => $this->iriConverter->getIriFromResource($object);
152✔
67
        }
68

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

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

83
        $class = $context['force_resource_class'] ?? $this->getObjectClass($data);
26✔
84
        if (($context['output']['class'] ?? null) === $class) {
26✔
85
            return true;
2✔
86
        }
87

88
        return $this->resourceClassResolver->isResourceClass($class);
24✔
89
    }
90

91
    public function getSupportedTypes(?string $format): array
92
    {
93
        return ['*' => true];
36✔
94
    }
95

96
    /**
97
     * {@inheritdoc}
98
     */
99
    public function hasCacheableSupportsMethod(): bool
100
    {
101
        if (method_exists(Serializer::class, 'getSupportedTypes')) {
×
102
            trigger_deprecation(
×
103
                'api-platform/core',
×
104
                '3.1',
×
105
                'The "%s()" method is deprecated, use "getSupportedTypes()" instead.',
×
106
                __METHOD__
×
107
            );
×
108
        }
109

110
        return true;
×
111
    }
112

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

126
            unset($context['output'], $context['operation'], $context['operation_name']);
2✔
127
            $context['resource_class'] = $outputClass;
2✔
128
            $context['api_sub_level'] = true;
2✔
129
            $context[self::ALLOW_EXTRA_ATTRIBUTES] = false;
2✔
130

131
            return $this->serializer->normalize($object, $format, $context);
2✔
132
        }
133

134
        if (isset($context['operation']) && $context['operation'] instanceof CollectionOperationInterface) {
46✔
135
            unset($context['operation_name']);
×
136
            unset($context['operation']);
×
137
            unset($context['iri']);
×
138
        }
139

140
        if ($this->resourceClassResolver->isResourceClass($resourceClass)) {
46✔
141
            $context = $this->initContext($resourceClass, $context);
44✔
142
        }
143

144
        $context['api_normalize'] = true;
46✔
145
        $iri = $context['iri'] ??= $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_URL, $context['operation'] ?? null, $context);
46✔
146

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

160
        if (isset($context['resources'])) {
46✔
161
            $context['resources'][$iri] = $iri;
32✔
162
        }
163

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

166
        if ($emptyResourceAsIri && \is_array($data) && 0 === \count($data)) {
44✔
167
            return $iri;
×
168
        }
169

170
        return $data;
44✔
171
    }
172

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

182
        return $this->localCache[$type] ?? $this->localCache[$type] = $this->resourceClassResolver->isResourceClass($type);
12✔
183
    }
184

185
    /**
186
     * {@inheritdoc}
187
     */
188
    public function denormalize(mixed $data, string $class, string $format = null, array $context = []): mixed
189
    {
190
        $resourceClass = $class;
60✔
191

192
        if ($inputClass = $this->getInputClass($context)) {
60✔
193
            if (!$this->serializer instanceof DenormalizerInterface) {
×
194
                throw new LogicException('Cannot denormalize the input because the injected serializer is not a denormalizer');
×
195
            }
196

197
            unset($context['input'], $context['operation'], $context['operation_name']);
×
198
            $context['resource_class'] = $inputClass;
×
199

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

207
        if (null === $objectToPopulate = $this->extractObjectToPopulate($resourceClass, $context, static::OBJECT_TO_POPULATE)) {
60✔
208
            $normalizedData = \is_scalar($data) ? [$data] : $this->prepareForDenormalization($data);
52✔
209
            $class = $this->getClassDiscriminatorResolvedClass($normalizedData, $class, $context);
52✔
210
        }
211

212
        $context['api_denormalize'] = true;
60✔
213

214
        if ($this->resourceClassResolver->isResourceClass($class)) {
60✔
215
            $resourceClass = $this->resourceClassResolver->getResourceClass($objectToPopulate, $class);
60✔
216
            $context['resource_class'] = $resourceClass;
60✔
217
        }
218

219
        if (\is_string($data)) {
60✔
220
            try {
221
                return $this->iriConverter->getResourceFromIri($data, $context + ['fetch_data' => true]);
×
222
            } catch (ItemNotFoundException $e) {
×
223
                throw new UnexpectedValueException($e->getMessage(), $e->getCode(), $e);
×
224
            } catch (InvalidArgumentException $e) {
×
225
                throw new UnexpectedValueException(sprintf('Invalid IRI "%s".', $data), $e->getCode(), $e);
×
226
            }
227
        }
228

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

233
        $previousObject = $this->clone($objectToPopulate);
60✔
234
        $object = parent::denormalize($data, $class, $format, $context);
60✔
235

236
        if (!$this->resourceClassResolver->isResourceClass($class)) {
46✔
237
            return $object;
×
238
        }
239

240
        // Bypass the post-denormalize attribute revert logic if the object could not be
241
        // cloned since we cannot possibly revert any changes made to it.
242
        if (null !== $objectToPopulate && null === $previousObject) {
46✔
243
            return $object;
2✔
244
        }
245

246
        $options = $this->getFactoryOptions($context);
44✔
247
        $propertyNames = iterator_to_array($this->propertyNameCollectionFactory->create($resourceClass, $options));
44✔
248

249
        // Revert attributes that aren't allowed to be changed after a post-denormalize check
250
        foreach (array_keys($data) as $attribute) {
44✔
251
            $attribute = $this->nameConverter ? $this->nameConverter->denormalize((string) $attribute) : $attribute;
44✔
252
            if (!\in_array($attribute, $propertyNames, true)) {
44✔
253
                continue;
2✔
254
            }
255

256
            if (!$this->canAccessAttributePostDenormalize($object, $previousObject, $attribute, $context)) {
44✔
257
                if (null !== $previousObject) {
4✔
258
                    $this->setValue($object, $attribute, $this->propertyAccessor->getValue($previousObject, $attribute));
2✔
259
                } else {
260
                    $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $attribute, $options);
2✔
261
                    $this->setValue($object, $attribute, $propertyMetadata->getDefault());
2✔
262
                }
263
            }
264
        }
265

266
        return $object;
44✔
267
    }
268

269
    /**
270
     * Method copy-pasted from symfony/serializer.
271
     * Remove it after symfony/serializer version update @see https://github.com/symfony/symfony/pull/28263.
272
     *
273
     * {@inheritdoc}
274
     *
275
     * @internal
276
     */
277
    protected function instantiateObject(array &$data, string $class, array &$context, \ReflectionClass $reflectionClass, array|bool $allowedAttributes, string $format = null): object
278
    {
279
        if (null !== $object = $this->extractObjectToPopulate($class, $context, static::OBJECT_TO_POPULATE)) {
60✔
280
            unset($context[static::OBJECT_TO_POPULATE]);
8✔
281

282
            return $object;
8✔
283
        }
284

285
        $class = $this->getClassDiscriminatorResolvedClass($data, $class, $context);
52✔
286
        $reflectionClass = new \ReflectionClass($class);
52✔
287

288
        $constructor = $this->getConstructor($data, $class, $context, $reflectionClass, $allowedAttributes);
52✔
289
        if ($constructor) {
52✔
290
            $constructorParameters = $constructor->getParameters();
48✔
291

292
            $params = [];
48✔
293
            foreach ($constructorParameters as $constructorParameter) {
48✔
294
                $paramName = $constructorParameter->name;
×
295
                $key = $this->nameConverter ? $this->nameConverter->normalize($paramName, $class, $format, $context) : $paramName;
×
296

297
                $allowed = false === $allowedAttributes || (\is_array($allowedAttributes) && \in_array($paramName, $allowedAttributes, true));
×
298
                $ignored = !$this->isAllowedAttribute($class, $paramName, $format, $context);
×
299
                if ($constructorParameter->isVariadic()) {
×
300
                    if ($allowed && !$ignored && (isset($data[$key]) || \array_key_exists($key, $data))) {
×
301
                        if (!\is_array($data[$paramName])) {
×
302
                            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));
×
303
                        }
304

305
                        $params[] = $data[$paramName];
×
306
                    }
307
                } elseif ($allowed && !$ignored && (isset($data[$key]) || \array_key_exists($key, $data))) {
×
308
                    $constructorContext = $context;
×
309
                    $constructorContext['deserialization_path'] = $context['deserialization_path'] ?? $key;
×
310
                    try {
311
                        $params[] = $this->createConstructorArgument($data[$key], $key, $constructorParameter, $constructorContext, $format);
×
312
                    } catch (NotNormalizableValueException $exception) {
×
313
                        if (!isset($context['not_normalizable_value_exceptions'])) {
×
314
                            throw $exception;
×
315
                        }
316
                        $context['not_normalizable_value_exceptions'][] = $exception;
×
317
                    }
318

319
                    // Don't run set for a parameter passed to the constructor
320
                    unset($data[$key]);
×
321
                } elseif (isset($context[static::DEFAULT_CONSTRUCTOR_ARGUMENTS][$class][$key])) {
×
322
                    $params[] = $context[static::DEFAULT_CONSTRUCTOR_ARGUMENTS][$class][$key];
×
323
                } elseif ($constructorParameter->isDefaultValueAvailable()) {
×
324
                    $params[] = $constructorParameter->getDefaultValue();
×
325
                } else {
326
                    if (!isset($context['not_normalizable_value_exceptions'])) {
×
327
                        throw new MissingConstructorArgumentsException(sprintf('Cannot create an instance of "%s" from serialized data because its constructor requires parameter "%s" to be present.', $class, $constructorParameter->name), 0, null, [$constructorParameter->name]);
×
328
                    }
329

330
                    $exception = NotNormalizableValueException::createForUnexpectedDataType(sprintf('Failed to create object because the class misses the "%s" property.', $constructorParameter->name), $data, ['unknown'], $context['deserialization_path'] ?? null, true);
×
331
                    $context['not_normalizable_value_exceptions'][] = $exception;
×
332
                }
333
            }
334

335
            if (\count($context['not_normalizable_value_exceptions'] ?? []) > 0) {
48✔
336
                return $reflectionClass->newInstanceWithoutConstructor();
×
337
            }
338

339
            if ($constructor->isConstructor()) {
48✔
340
                return $reflectionClass->newInstanceArgs($params);
48✔
341
            }
342

343
            return $constructor->invokeArgs(null, $params);
×
344
        }
345

346
        return new $class();
4✔
347
    }
348

349
    protected function getClassDiscriminatorResolvedClass(array $data, string $class, array $context = []): string
350
    {
351
        if (null === $this->classDiscriminatorResolver || (null === $mapping = $this->classDiscriminatorResolver->getMappingForClass($class))) {
52✔
352
            return $class;
52✔
353
        }
354

355
        if (!isset($data[$mapping->getTypeProperty()])) {
×
356
            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());
×
357
        }
358

359
        $type = $data[$mapping->getTypeProperty()];
×
360
        if (null === ($mappedClass = $mapping->getClassForType($type))) {
×
361
            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);
×
362
        }
363

364
        return $mappedClass;
×
365
    }
366

367
    protected function createConstructorArgument($parameterData, string $key, \ReflectionParameter $constructorParameter, array &$context, string $format = null): mixed
368
    {
369
        return $this->createAndValidateAttributeValue($constructorParameter->name, $parameterData, $format, $context);
×
370
    }
371

372
    /**
373
     * {@inheritdoc}
374
     *
375
     * Unused in this context.
376
     *
377
     * @return string[]
378
     */
379
    protected function extractAttributes($object, $format = null, array $context = []): array
380
    {
381
        return [];
×
382
    }
383

384
    /**
385
     * {@inheritdoc}
386
     */
387
    protected function getAllowedAttributes(string|object $classOrObject, array $context, bool $attributesAsString = false): array|bool
388
    {
389
        if (!$this->resourceClassResolver->isResourceClass($context['resource_class'])) {
98✔
390
            return parent::getAllowedAttributes($classOrObject, $context, $attributesAsString);
2✔
391
        }
392

393
        $resourceClass = $this->resourceClassResolver->getResourceClass(null, $context['resource_class']); // fix for abstract classes and interfaces
96✔
394
        $options = $this->getFactoryOptions($context);
96✔
395
        $propertyNames = $this->propertyNameCollectionFactory->create($resourceClass, $options);
96✔
396

397
        $allowedAttributes = [];
96✔
398
        foreach ($propertyNames as $propertyName) {
96✔
399
            $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $propertyName, $options);
96✔
400

401
            if (
402
                $this->isAllowedAttribute($classOrObject, $propertyName, null, $context)
96✔
403
                && (
404
                    isset($context['api_normalize']) && $propertyMetadata->isReadable()
96✔
405
                    || isset($context['api_denormalize']) && ($propertyMetadata->isWritable() || !\is_object($classOrObject) && $propertyMetadata->isInitializable())
96✔
406
                )
407
            ) {
408
                $allowedAttributes[] = $propertyName;
96✔
409
            }
410
        }
411

412
        return $allowedAttributes;
96✔
413
    }
414

415
    /**
416
     * {@inheritdoc}
417
     */
418
    protected function isAllowedAttribute(object|string $classOrObject, string $attribute, string $format = null, array $context = []): bool
419
    {
420
        if (!parent::isAllowedAttribute($classOrObject, $attribute, $format, $context)) {
98✔
421
            return false;
2✔
422
        }
423

424
        return $this->canAccessAttribute(\is_object($classOrObject) ? $classOrObject : null, $attribute, $context);
98✔
425
    }
426

427
    /**
428
     * Check if access to the attribute is granted.
429
     */
430
    protected function canAccessAttribute(?object $object, string $attribute, array $context = []): bool
431
    {
432
        if (!$this->resourceClassResolver->isResourceClass($context['resource_class'])) {
98✔
433
            return true;
2✔
434
        }
435

436
        $options = $this->getFactoryOptions($context);
96✔
437
        $propertyMetadata = $this->propertyMetadataFactory->create($context['resource_class'], $attribute, $options);
96✔
438
        $security = $propertyMetadata->getSecurity();
96✔
439
        if (null !== $this->resourceAccessChecker && $security) {
96✔
440
            return $this->resourceAccessChecker->isGranted($context['resource_class'], $security, [
8✔
441
                'object' => $object,
8✔
442
            ]);
8✔
443
        }
444

445
        return true;
96✔
446
    }
447

448
    /**
449
     * Check if access to the attribute is granted.
450
     */
451
    protected function canAccessAttributePostDenormalize(?object $object, ?object $previousObject, string $attribute, array $context = []): bool
452
    {
453
        $options = $this->getFactoryOptions($context);
44✔
454
        $propertyMetadata = $this->propertyMetadataFactory->create($context['resource_class'], $attribute, $options);
44✔
455
        $security = $propertyMetadata->getSecurityPostDenormalize();
44✔
456
        if ($this->resourceAccessChecker && $security) {
44✔
457
            return $this->resourceAccessChecker->isGranted($context['resource_class'], $security, [
4✔
458
                'object' => $object,
4✔
459
                'previous_object' => $previousObject,
4✔
460
            ]);
4✔
461
        }
462

463
        return true;
44✔
464
    }
465

466
    /**
467
     * {@inheritdoc}
468
     */
469
    protected function setAttributeValue(object $object, string $attribute, mixed $value, string $format = null, array $context = []): void
470
    {
471
        try {
472
            $this->setValue($object, $attribute, $this->createAttributeValue($attribute, $value, $format, $context));
60✔
473
        } catch (NotNormalizableValueException $exception) {
14✔
474
            // Only throw if collecting denormalization errors is disabled.
475
            if (!isset($context['not_normalizable_value_exceptions'])) {
10✔
476
                throw $exception;
10✔
477
            }
478
        }
479
    }
480

481
    /**
482
     * Validates the type of the value. Allows using integers as floats for JSON formats.
483
     *
484
     * @throws NotNormalizableValueException
485
     */
486
    protected function validateType(string $attribute, Type $type, mixed $value, string $format = null, array $context = []): void
487
    {
488
        $builtinType = $type->getBuiltinType();
30✔
489
        if (Type::BUILTIN_TYPE_FLOAT === $builtinType && null !== $format && str_contains($format, 'json')) {
30✔
490
            $isValid = \is_float($value) || \is_int($value);
2✔
491
        } else {
492
            $isValid = \call_user_func('is_'.$builtinType, $value);
28✔
493
        }
494

495
        if (!$isValid) {
30✔
496
            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);
2✔
497
        }
498
    }
499

500
    /**
501
     * Denormalizes a collection of objects.
502
     *
503
     * @throws NotNormalizableValueException
504
     */
505
    protected function denormalizeCollection(string $attribute, ApiProperty $propertyMetadata, Type $type, string $className, mixed $value, ?string $format, array $context): array
506
    {
507
        if (!\is_array($value)) {
14✔
508
            throw NotNormalizableValueException::createForUnexpectedDataType(sprintf('The type of the "%s" attribute must be "array", "%s" given.', $attribute, \gettype($value)), $value, [Type::BUILTIN_TYPE_ARRAY], $context['deserialization_path'] ?? null);
2✔
509
        }
510

511
        $collectionKeyType = $type->getCollectionKeyTypes()[0] ?? null;
12✔
512
        $collectionKeyBuiltinType = $collectionKeyType?->getBuiltinType();
12✔
513
        $childContext = $this->createChildContext(['resource_class' => $className] + $context, $attribute, $format);
12✔
514
        unset($childContext['uri_variables']);
12✔
515
        if ($this->resourceMetadataCollectionFactory) {
12✔
516
            $childContext['operation'] = $this->resourceMetadataCollectionFactory->create($className)->getOperation();
2✔
517
        }
518

519
        $values = [];
12✔
520
        foreach ($value as $index => $obj) {
12✔
521
            if (null !== $collectionKeyBuiltinType && !\call_user_func('is_'.$collectionKeyBuiltinType, $index)) {
12✔
522
                throw NotNormalizableValueException::createForUnexpectedDataType(sprintf('The type of the key "%s" must be "%s", "%s" given.', $index, $collectionKeyBuiltinType, \gettype($index)), $index, [$collectionKeyBuiltinType], ($context['deserialization_path'] ?? false) ? sprintf('key(%s)', $context['deserialization_path']) : null, true);
4✔
523
            }
524

525
            $values[$index] = $this->denormalizeRelation($attribute, $propertyMetadata, $className, $obj, $format, $childContext);
8✔
526
        }
527

528
        return $values;
8✔
529
    }
530

531
    /**
532
     * Denormalizes a relation.
533
     *
534
     * @throws LogicException
535
     * @throws UnexpectedValueException
536
     * @throws NotNormalizableValueException
537
     */
538
    protected function denormalizeRelation(string $attributeName, ApiProperty $propertyMetadata, string $className, mixed $value, ?string $format, array $context): ?object
539
    {
540
        if (\is_string($value)) {
10✔
541
            try {
542
                return $this->iriConverter->getResourceFromIri($value, $context + ['fetch_data' => true]);
2✔
543
            } catch (ItemNotFoundException $e) {
×
544
                throw new UnexpectedValueException($e->getMessage(), $e->getCode(), $e);
×
545
            } catch (InvalidArgumentException $e) {
×
546
                throw new UnexpectedValueException(sprintf('Invalid IRI "%s".', $value), $e->getCode(), $e);
×
547
            }
548
        }
549

550
        if ($propertyMetadata->isWritableLink()) {
8✔
551
            $context['api_allow_update'] = true;
4✔
552

553
            if (!$this->serializer instanceof DenormalizerInterface) {
4✔
554
                throw new LogicException(sprintf('The injected serializer must be an instance of "%s".', DenormalizerInterface::class));
×
555
            }
556

557
            $item = $this->serializer->denormalize($value, $className, $format, $context);
4✔
558
            if (!\is_object($item) && null !== $item) {
4✔
559
                throw new \UnexpectedValueException('Expected item to be an object or null.');
×
560
            }
561

562
            return $item;
4✔
563
        }
564

565
        if (!\is_array($value)) {
4✔
566
            throw NotNormalizableValueException::createForUnexpectedDataType(sprintf('The type of the "%s" attribute must be "array" (nested document) or "string" (IRI), "%s" given.', $attributeName, \gettype($value)), $value, [Type::BUILTIN_TYPE_ARRAY, Type::BUILTIN_TYPE_STRING], $context['deserialization_path'] ?? null);
2✔
567
        }
568

569
        throw new UnexpectedValueException(sprintf('Nested documents for attribute "%s" are not allowed. Use IRIs instead.', $attributeName));
2✔
570
    }
571

572
    /**
573
     * Gets the options for the property name collection / property metadata factories.
574
     */
575
    protected function getFactoryOptions(array $context): array
576
    {
577
        $options = [];
98✔
578
        if (isset($context[self::GROUPS])) {
98✔
579
            /* @see https://github.com/symfony/symfony/blob/v4.2.6/src/Symfony/Component/PropertyInfo/Extractor/SerializerExtractor.php */
580
            $options['serializer_groups'] = (array) $context[self::GROUPS];
2✔
581
        }
582

583
        $operationCacheKey = ($context['resource_class'] ?? '').($context['operation_name'] ?? '').($context['api_normalize'] ?? '');
98✔
584
        if ($operationCacheKey && isset($this->localFactoryOptionsCache[$operationCacheKey])) {
98✔
585
            return $options + $this->localFactoryOptionsCache[$operationCacheKey];
98✔
586
        }
587

588
        // This is a hot spot
589
        if (isset($context['resource_class'])) {
98✔
590
            // Note that the groups need to be read on the root operation
591
            $operation = $context['root_operation'] ?? $context['operation'] ?? null;
98✔
592

593
            if (!$operation && $this->resourceMetadataCollectionFactory && $this->resourceClassResolver->isResourceClass($context['resource_class'])) {
98✔
594
                $resourceClass = $this->resourceClassResolver->getResourceClass(null, $context['resource_class']); // fix for abstract classes and interfaces
10✔
595
                $operation = $this->resourceMetadataCollectionFactory->create($resourceClass)->getOperation($context['root_operation_name'] ?? $context['operation_name'] ?? null);
10✔
596
            }
597

598
            if ($operation) {
98✔
599
                $options['normalization_groups'] = $operation->getNormalizationContext()['groups'] ?? null;
24✔
600
                $options['denormalization_groups'] = $operation->getDenormalizationContext()['groups'] ?? null;
24✔
601
                $options['operation_name'] = $operation->getName();
24✔
602
            }
603
        }
604

605
        return $options + $this->localFactoryOptionsCache[$operationCacheKey] = $options;
98✔
606
    }
607

608
    /**
609
     * {@inheritdoc}
610
     *
611
     * @throws UnexpectedValueException
612
     */
613
    protected function getAttributeValue(object $object, string $attribute, string $format = null, array $context = []): mixed
614
    {
615
        $context['api_attribute'] = $attribute;
44✔
616
        $propertyMetadata = $this->propertyMetadataFactory->create($context['resource_class'], $attribute, $this->getFactoryOptions($context));
44✔
617

618
        $attributeValue = $this->propertyAccessor->getValue($object, $attribute);
44✔
619

620
        if ($context['api_denormalize'] ?? false) {
42✔
621
            return $attributeValue;
×
622
        }
623

624
        $type = $propertyMetadata->getBuiltinTypes()[0] ?? null;
42✔
625

626
        if (
627
            $type
42✔
628
            && $type->isCollection()
42✔
629
            && ($collectionValueType = $type->getCollectionValueTypes()[0] ?? null)
42✔
630
            && ($className = $collectionValueType->getClassName())
42✔
631
            && $this->resourceClassResolver->isResourceClass($className)
42✔
632
        ) {
633
            if (!is_iterable($attributeValue)) {
14✔
634
                throw new UnexpectedValueException('Unexpected non-iterable value for to-many relation.');
×
635
            }
636

637
            $resourceClass = $this->resourceClassResolver->getResourceClass($attributeValue, $className);
14✔
638
            $childContext = $this->createChildContext($context, $attribute, $format);
14✔
639
            unset($childContext['iri'], $childContext['uri_variables'], $childContext['resource_class'], $childContext['operation']);
14✔
640

641
            return $this->normalizeCollectionOfRelations($propertyMetadata, $attributeValue, $resourceClass, $format, $childContext);
14✔
642
        }
643

644
        if (
645
            $type
40✔
646
            && ($className = $type->getClassName())
40✔
647
            && $this->resourceClassResolver->isResourceClass($className)
40✔
648
        ) {
649
            if (!\is_object($attributeValue) && null !== $attributeValue) {
16✔
650
                throw new UnexpectedValueException('Unexpected non-object value for to-one relation.');
×
651
            }
652

653
            $resourceClass = $this->resourceClassResolver->getResourceClass($attributeValue, $className);
16✔
654
            $childContext = $this->createChildContext($context, $attribute, $format);
16✔
655
            $childContext['resource_class'] = $resourceClass;
16✔
656
            if ($this->resourceMetadataCollectionFactory) {
16✔
657
                $childContext['operation'] = $this->resourceMetadataCollectionFactory->create($resourceClass)->getOperation();
6✔
658
            }
659
            unset($childContext['iri'], $childContext['uri_variables']);
16✔
660

661
            return $this->normalizeRelation($propertyMetadata, $attributeValue, $resourceClass, $format, $childContext);
16✔
662
        }
663

664
        if (!$this->serializer instanceof NormalizerInterface) {
38✔
665
            throw new LogicException(sprintf('The injected serializer must be an instance of "%s".', NormalizerInterface::class));
×
666
        }
667

668
        unset($context['resource_class']);
38✔
669
        unset($context['force_resource_class']);
38✔
670

671
        if ($type && $type->getClassName()) {
38✔
672
            $childContext = $this->createChildContext($context, $attribute, $format);
6✔
673
            unset($childContext['iri'], $childContext['uri_variables']);
6✔
674
            $childContext['output']['gen_id'] = $propertyMetadata->getGenId() ?? true;
6✔
675

676
            return $this->serializer->normalize($attributeValue, $format, $childContext);
6✔
677
        }
678

679
        if ($type && 'array' === $type->getBuiltinType()) {
38✔
680
            $childContext = $this->createChildContext($context, $attribute, $format);
8✔
681
            unset($childContext['iri'], $childContext['uri_variables']);
8✔
682

683
            return $this->serializer->normalize($attributeValue, $format, $childContext);
8✔
684
        }
685

686
        return $this->serializer->normalize($attributeValue, $format, $context);
38✔
687
    }
688

689
    /**
690
     * Normalizes a collection of relations (to-many).
691
     *
692
     * @throws UnexpectedValueException
693
     */
694
    protected function normalizeCollectionOfRelations(ApiProperty $propertyMetadata, iterable $attributeValue, string $resourceClass, ?string $format, array $context): array
695
    {
696
        $value = [];
14✔
697
        foreach ($attributeValue as $index => $obj) {
14✔
698
            if (!\is_object($obj) && null !== $obj) {
6✔
699
                throw new UnexpectedValueException('Unexpected non-object element in to-many relation.');
×
700
            }
701

702
            // update context, if concrete object class deviates from general relation class (e.g. in case of polymorphic resources)
703
            $objResourceClass = $this->resourceClassResolver->getResourceClass($obj, $resourceClass);
6✔
704
            $context['resource_class'] = $objResourceClass;
6✔
705
            if ($this->resourceMetadataCollectionFactory) {
6✔
706
                $context['operation'] = $this->resourceMetadataCollectionFactory->create($objResourceClass)->getOperation();
×
707
            }
708

709
            $value[$index] = $this->normalizeRelation($propertyMetadata, $obj, $resourceClass, $format, $context);
6✔
710
        }
711

712
        return $value;
14✔
713
    }
714

715
    /**
716
     * Normalizes a relation.
717
     *
718
     * @throws LogicException
719
     * @throws UnexpectedValueException
720
     */
721
    protected function normalizeRelation(ApiProperty $propertyMetadata, ?object $relatedObject, string $resourceClass, ?string $format, array $context): \ArrayObject|array|string|null
722
    {
723
        if (null === $relatedObject || !empty($context['attributes']) || $propertyMetadata->isReadableLink()) {
18✔
724
            if (!$this->serializer instanceof NormalizerInterface) {
12✔
725
                throw new LogicException(sprintf('The injected serializer must be an instance of "%s".', NormalizerInterface::class));
×
726
            }
727

728
            $relatedContext = $context;
12✔
729
            unset($relatedContext['force_resource_class']);
12✔
730
            $normalizedRelatedObject = $this->serializer->normalize($relatedObject, $format, $relatedContext);
12✔
731
            if (!\is_string($normalizedRelatedObject) && !\is_array($normalizedRelatedObject) && !$normalizedRelatedObject instanceof \ArrayObject && null !== $normalizedRelatedObject) {
12✔
732
                throw new UnexpectedValueException('Expected normalized relation to be an IRI, array, \ArrayObject or null');
×
733
            }
734

735
            return $normalizedRelatedObject;
12✔
736
        }
737

738
        $iri = $this->iriConverter->getIriFromResource($relatedObject);
6✔
739

740
        if (isset($context['resources'])) {
6✔
741
            $context['resources'][$iri] = $iri;
2✔
742
        }
743

744
        $push = $propertyMetadata->getPush() ?? false;
6✔
745
        if (isset($context['resources_to_push']) && $push) {
6✔
746
            $context['resources_to_push'][$iri] = $iri;
×
747
        }
748

749
        return $iri;
6✔
750
    }
751

752
    private function createAttributeValue(string $attribute, mixed $value, string $format = null, array &$context = []): mixed
753
    {
754
        try {
755
            return $this->createAndValidateAttributeValue($attribute, $value, $format, $context);
60✔
756
        } catch (NotNormalizableValueException $exception) {
14✔
757
            if (!isset($context['not_normalizable_value_exceptions'])) {
10✔
758
                throw $exception;
10✔
759
            }
760
            $context['not_normalizable_value_exceptions'][] = $exception;
×
761

762
            throw $exception;
×
763
        }
764
    }
765

766
    private function createAndValidateAttributeValue(string $attribute, mixed $value, string $format = null, array $context = []): mixed
767
    {
768
        $propertyMetadata = $this->propertyMetadataFactory->create($context['resource_class'], $attribute, $this->getFactoryOptions($context));
60✔
769
        $type = $propertyMetadata->getBuiltinTypes()[0] ?? null;
60✔
770

771
        if (null === $type) {
60✔
772
            // No type provided, blindly return the value
773
            return $value;
10✔
774
        }
775

776
        if (null === $value && $type->isNullable() || ($context[static::DISABLE_TYPE_ENFORCEMENT] ?? false)) {
50✔
777
            return $value;
6✔
778
        }
779

780
        $collectionValueType = $type->getCollectionValueTypes()[0] ?? null;
44✔
781

782
        /* From @see AbstractObjectNormalizer::validateAndDenormalize() */
783
        // Fix a collection that contains the only one element
784
        // This is special to xml format only
785
        if ('xml' === $format && null !== $collectionValueType && (!\is_array($value) || !\is_int(key($value)))) {
44✔
786
            $value = [$value];
2✔
787
        }
788

789
        if (
790
            $type->isCollection()
44✔
791
            && null !== $collectionValueType
44✔
792
            && null !== ($className = $collectionValueType->getClassName())
44✔
793
            && $this->resourceClassResolver->isResourceClass($className)
44✔
794
        ) {
795
            $resourceClass = $this->resourceClassResolver->getResourceClass(null, $className);
14✔
796

797
            return $this->denormalizeCollection($attribute, $propertyMetadata, $type, $resourceClass, $value, $format, $context);
14✔
798
        }
799

800
        if (
801
            null !== ($className = $type->getClassName())
36✔
802
            && $this->resourceClassResolver->isResourceClass($className)
36✔
803
        ) {
804
            $resourceClass = $this->resourceClassResolver->getResourceClass(null, $className);
12✔
805
            $childContext = $this->createChildContext($context, $attribute, $format);
12✔
806
            $childContext['resource_class'] = $resourceClass;
12✔
807
            unset($childContext['uri_variables']);
12✔
808
            if ($this->resourceMetadataCollectionFactory) {
12✔
809
                $childContext['operation'] = $this->resourceMetadataCollectionFactory->create($resourceClass)->getOperation();
2✔
810
            }
811

812
            return $this->denormalizeRelation($attribute, $propertyMetadata, $resourceClass, $value, $format, $childContext);
12✔
813
        }
814

815
        if (
816
            $type->isCollection()
30✔
817
            && null !== $collectionValueType
30✔
818
            && null !== ($className = $collectionValueType->getClassName())
30✔
819
        ) {
820
            if (!$this->serializer instanceof DenormalizerInterface) {
×
821
                throw new LogicException(sprintf('The injected serializer must be an instance of "%s".', DenormalizerInterface::class));
×
822
            }
823

824
            unset($context['resource_class']);
×
825

826
            return $this->serializer->denormalize($value, $className.'[]', $format, $context);
×
827
        }
828

829
        if (null !== $className = $type->getClassName()) {
30✔
830
            if (!$this->serializer instanceof DenormalizerInterface) {
×
831
                throw new LogicException(sprintf('The injected serializer must be an instance of "%s".', DenormalizerInterface::class));
×
832
            }
833

834
            unset($context['resource_class']);
×
835

836
            return $this->serializer->denormalize($value, $className, $format, $context);
×
837
        }
838

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

848
            switch ($type->getBuiltinType()) {
2✔
849
                case Type::BUILTIN_TYPE_BOOL:
850
                    // according to http://www.w3.org/TR/xmlschema-2/#boolean, valid representations are "false", "true", "0" and "1"
851
                    if ('false' === $value || '0' === $value) {
2✔
852
                        $value = false;
2✔
853
                    } elseif ('true' === $value || '1' === $value) {
2✔
854
                        $value = true;
2✔
855
                    } else {
856
                        throw NotNormalizableValueException::createForUnexpectedDataType(sprintf('The type of the "%s" attribute for class "%s" must be bool ("%s" given).', $attribute, $className, $value), $value, [Type::BUILTIN_TYPE_BOOL], $context['deserialization_path'] ?? null);
×
857
                    }
858
                    break;
2✔
859
                case Type::BUILTIN_TYPE_INT:
860
                    if (ctype_digit($value) || ('-' === $value[0] && ctype_digit(substr($value, 1)))) {
2✔
861
                        $value = (int) $value;
2✔
862
                    } else {
863
                        throw NotNormalizableValueException::createForUnexpectedDataType(sprintf('The type of the "%s" attribute for class "%s" must be int ("%s" given).', $attribute, $className, $value), $value, [Type::BUILTIN_TYPE_INT], $context['deserialization_path'] ?? null);
×
864
                    }
865
                    break;
2✔
866
                case Type::BUILTIN_TYPE_FLOAT:
867
                    if (is_numeric($value)) {
2✔
868
                        return (float) $value;
2✔
869
                    }
870

871
                    return match ($value) {
2✔
872
                        'NaN' => \NAN,
2✔
873
                        'INF' => \INF,
2✔
874
                        '-INF' => -\INF,
2✔
875
                        default => throw NotNormalizableValueException::createForUnexpectedDataType(sprintf('The type of the "%s" attribute for class "%s" must be float ("%s" given).', $attribute, $className, $value), $value, [Type::BUILTIN_TYPE_FLOAT], $context['deserialization_path'] ?? null),
2✔
876
                    };
2✔
877
            }
878
        }
879

880
        if ($context[static::DISABLE_TYPE_ENFORCEMENT] ?? false) { // @phpstan-ignore-line
30✔
881
            return $value;
×
882
        }
883

884
        $this->validateType($attribute, $type, $value, $format, $context);
30✔
885

886
        return $value;
28✔
887
    }
888

889
    /**
890
     * Sets a value of the object using the PropertyAccess component.
891
     */
892
    private function setValue(object $object, string $attributeName, mixed $value): void
893
    {
894
        try {
895
            $this->propertyAccessor->setValue($object, $attributeName, $value);
46✔
896
        } catch (NoSuchPropertyException) {
2✔
897
            // Properties not found are ignored
898
        }
899
    }
900
}
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

© 2026 Coveralls, Inc