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

api-platform / core / 5155537119

pending completion
5155537119

push

github

web-flow
fix: enable API Platform integration in LexikJWTAuthenticationBundle (#5609)

6 of 6 new or added lines in 1 file covered. (100.0%)

10798 of 18112 relevant lines covered (59.62%)

20.13 hits per line

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

77.26
/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

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

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

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

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

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

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

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

90
    /**
91
     * {@inheritdoc}
92
     */
93
    public function hasCacheableSupportsMethod(): bool
94
    {
95
        return true;
36✔
96
    }
97

98
    /**
99
     * {@inheritdoc}
100
     *
101
     * @throws LogicException
102
     */
103
    public function normalize(mixed $object, string $format = null, array $context = []): array|string|int|float|bool|\ArrayObject|null
104
    {
105
        $resourceClass = $context['force_resource_class'] ?? $this->getObjectClass($object);
46✔
106
        if ($outputClass = $this->getOutputClass($context)) {
46✔
107
            if (!$this->serializer instanceof NormalizerInterface) {
2✔
108
                throw new LogicException('Cannot normalize the output because the injected serializer is not a normalizer');
×
109
            }
110

111
            unset($context['output'], $context['operation'], $context['operation_name']);
2✔
112
            $context['resource_class'] = $outputClass;
2✔
113
            $context['api_sub_level'] = true;
2✔
114
            $context[self::ALLOW_EXTRA_ATTRIBUTES] = false;
2✔
115

116
            return $this->serializer->normalize($object, $format, $context);
2✔
117
        }
118

119
        if (isset($context['operation']) && $context['operation'] instanceof CollectionOperationInterface) {
46✔
120
            unset($context['operation_name']);
×
121
            unset($context['operation']);
×
122
            unset($context['iri']);
×
123
        }
124

125
        if ($this->resourceClassResolver->isResourceClass($resourceClass)) {
46✔
126
            $context = $this->initContext($resourceClass, $context);
44✔
127
        }
128

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

132
        /*
133
         * When true, converts the normalized data array of a resource into an
134
         * IRI, if the normalized data array is empty.
135
         *
136
         * This is useful when traversing from a non-resource towards an attribute
137
         * which is a resource, as we do not have the benefit of {@see ApiProperty::isReadableLink}.
138
         *
139
         * It must not be propagated to resources, as {@see ApiProperty::isReadableLink}
140
         * should take effect.
141
         */
142
        $emptyResourceAsIri = $context['api_empty_resource_as_iri'] ?? false;
46✔
143
        unset($context['api_empty_resource_as_iri']);
46✔
144

145
        if (isset($context['resources'])) {
46✔
146
            $context['resources'][$iri] = $iri;
32✔
147
        }
148

149
        $data = parent::normalize($object, $format, $context);
46✔
150

151
        if ($emptyResourceAsIri && \is_array($data) && 0 === \count($data)) {
42✔
152
            return $iri;
×
153
        }
154

155
        return $data;
42✔
156
    }
157

158
    /**
159
     * {@inheritdoc}
160
     */
161
    public function supportsDenormalization(mixed $data, string $type, string $format = null, array $context = []): bool
162
    {
163
        if (($context['input']['class'] ?? null) === $type) {
12✔
164
            return true;
×
165
        }
166

167
        return $this->localCache[$type] ?? $this->localCache[$type] = $this->resourceClassResolver->isResourceClass($type);
12✔
168
    }
169

170
    /**
171
     * {@inheritdoc}
172
     */
173
    public function denormalize(mixed $data, string $class, string $format = null, array $context = []): mixed
174
    {
175
        $resourceClass = $class;
60✔
176

177
        if ($inputClass = $this->getInputClass($context)) {
60✔
178
            if (!$this->serializer instanceof DenormalizerInterface) {
×
179
                throw new LogicException('Cannot normalize the output because the injected serializer is not a normalizer');
×
180
            }
181

182
            unset($context['input'], $context['operation'], $context['operation_name']);
×
183
            $context['resource_class'] = $inputClass;
×
184

185
            try {
186
                return $this->serializer->denormalize($data, $inputClass, $format, $context);
×
187
            } catch (NotNormalizableValueException $e) {
×
188
                throw new UnexpectedValueException('The input data is misformatted.', $e->getCode(), $e);
×
189
            }
190
        }
191

192
        if (null === $objectToPopulate = $this->extractObjectToPopulate($resourceClass, $context, static::OBJECT_TO_POPULATE)) {
60✔
193
            $normalizedData = \is_scalar($data) ? [$data] : $this->prepareForDenormalization($data);
52✔
194
            $class = $this->getClassDiscriminatorResolvedClass($normalizedData, $class, $context);
52✔
195
        }
196

197
        $context['api_denormalize'] = true;
60✔
198

199
        if ($this->resourceClassResolver->isResourceClass($class)) {
60✔
200
            $resourceClass = $this->resourceClassResolver->getResourceClass($objectToPopulate, $class);
60✔
201
            $context['resource_class'] = $resourceClass;
60✔
202
        }
203

204
        if (\is_string($data)) {
60✔
205
            try {
206
                return $this->iriConverter->getResourceFromIri($data, $context + ['fetch_data' => true]);
×
207
            } catch (ItemNotFoundException $e) {
×
208
                throw new UnexpectedValueException($e->getMessage(), $e->getCode(), $e);
×
209
            } catch (InvalidArgumentException $e) {
×
210
                throw new UnexpectedValueException(sprintf('Invalid IRI "%s".', $data), $e->getCode(), $e);
×
211
            }
212
        }
213

214
        if (!\is_array($data)) {
60✔
215
            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);
×
216
        }
217

218
        $previousObject = $this->clone($objectToPopulate);
60✔
219
        $object = parent::denormalize($data, $class, $format, $context);
60✔
220

221
        if (!$this->resourceClassResolver->isResourceClass($class)) {
46✔
222
            return $object;
×
223
        }
224

225
        // Bypass the post-denormalize attribute revert logic if the object could not be
226
        // cloned since we cannot possibly revert any changes made to it.
227
        if (null !== $objectToPopulate && null === $previousObject) {
46✔
228
            return $object;
2✔
229
        }
230

231
        $options = $this->getFactoryOptions($context);
44✔
232
        $propertyNames = iterator_to_array($this->propertyNameCollectionFactory->create($resourceClass, $options));
44✔
233

234
        // Revert attributes that aren't allowed to be changed after a post-denormalize check
235
        foreach (array_keys($data) as $attribute) {
44✔
236
            $attribute = $this->nameConverter ? $this->nameConverter->denormalize((string) $attribute) : $attribute;
44✔
237
            if (!\in_array($attribute, $propertyNames, true)) {
44✔
238
                continue;
2✔
239
            }
240

241
            if (!$this->canAccessAttributePostDenormalize($object, $previousObject, $attribute, $context)) {
44✔
242
                if (null !== $previousObject) {
4✔
243
                    $this->setValue($object, $attribute, $this->propertyAccessor->getValue($previousObject, $attribute));
2✔
244
                } else {
245
                    $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $attribute, $options);
2✔
246
                    $this->setValue($object, $attribute, $propertyMetadata->getDefault());
2✔
247
                }
248
            }
249
        }
250

251
        return $object;
44✔
252
    }
253

254
    /**
255
     * Method copy-pasted from symfony/serializer.
256
     * Remove it after symfony/serializer version update @see https://github.com/symfony/symfony/pull/28263.
257
     *
258
     * {@inheritdoc}
259
     *
260
     * @internal
261
     */
262
    protected function instantiateObject(array &$data, string $class, array &$context, \ReflectionClass $reflectionClass, array|bool $allowedAttributes, string $format = null): object
263
    {
264
        if (null !== $object = $this->extractObjectToPopulate($class, $context, static::OBJECT_TO_POPULATE)) {
60✔
265
            unset($context[static::OBJECT_TO_POPULATE]);
8✔
266

267
            return $object;
8✔
268
        }
269

270
        $class = $this->getClassDiscriminatorResolvedClass($data, $class, $context);
52✔
271
        $reflectionClass = new \ReflectionClass($class);
52✔
272

273
        $constructor = $this->getConstructor($data, $class, $context, $reflectionClass, $allowedAttributes);
52✔
274
        if ($constructor) {
52✔
275
            $constructorParameters = $constructor->getParameters();
48✔
276

277
            $params = [];
48✔
278
            foreach ($constructorParameters as $constructorParameter) {
48✔
279
                $paramName = $constructorParameter->name;
×
280
                $key = $this->nameConverter ? $this->nameConverter->normalize($paramName, $class, $format, $context) : $paramName;
×
281

282
                $allowed = false === $allowedAttributes || (\is_array($allowedAttributes) && \in_array($paramName, $allowedAttributes, true));
×
283
                $ignored = !$this->isAllowedAttribute($class, $paramName, $format, $context);
×
284
                if ($constructorParameter->isVariadic()) {
×
285
                    if ($allowed && !$ignored && (isset($data[$key]) || \array_key_exists($key, $data))) {
×
286
                        if (!\is_array($data[$paramName])) {
×
287
                            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));
×
288
                        }
289

290
                        $params[] = $data[$paramName];
×
291
                    }
292
                } elseif ($allowed && !$ignored && (isset($data[$key]) || \array_key_exists($key, $data))) {
×
293
                    $constructorContext = $context;
×
294
                    $constructorContext['deserialization_path'] = $context['deserialization_path'] ?? $key;
×
295
                    try {
296
                        $params[] = $this->createConstructorArgument($data[$key], $key, $constructorParameter, $constructorContext, $format);
×
297
                    } catch (NotNormalizableValueException $exception) {
×
298
                        if (!isset($context['not_normalizable_value_exceptions'])) {
×
299
                            throw $exception;
×
300
                        }
301
                        $context['not_normalizable_value_exceptions'][] = $exception;
×
302
                    }
303

304
                    // Don't run set for a parameter passed to the constructor
305
                    unset($data[$key]);
×
306
                } elseif (isset($context[static::DEFAULT_CONSTRUCTOR_ARGUMENTS][$class][$key])) {
×
307
                    $params[] = $context[static::DEFAULT_CONSTRUCTOR_ARGUMENTS][$class][$key];
×
308
                } elseif ($constructorParameter->isDefaultValueAvailable()) {
×
309
                    $params[] = $constructorParameter->getDefaultValue();
×
310
                } else {
311
                    if (!isset($context['not_normalizable_value_exceptions'])) {
×
312
                        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]);
×
313
                    }
314

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

320
            if (\count($context['not_normalizable_value_exceptions'] ?? []) > 0) {
48✔
321
                return $reflectionClass->newInstanceWithoutConstructor();
×
322
            }
323

324
            if ($constructor->isConstructor()) {
48✔
325
                return $reflectionClass->newInstanceArgs($params);
48✔
326
            }
327

328
            return $constructor->invokeArgs(null, $params);
×
329
        }
330

331
        return new $class();
4✔
332
    }
333

334
    protected function getClassDiscriminatorResolvedClass(array $data, string $class, array $context = []): string
335
    {
336
        if (null === $this->classDiscriminatorResolver || (null === $mapping = $this->classDiscriminatorResolver->getMappingForClass($class))) {
52✔
337
            return $class;
52✔
338
        }
339

340
        if (!isset($data[$mapping->getTypeProperty()])) {
×
341
            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());
×
342
        }
343

344
        $type = $data[$mapping->getTypeProperty()];
×
345
        if (null === ($mappedClass = $mapping->getClassForType($type))) {
×
346
            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);
×
347
        }
348

349
        return $mappedClass;
×
350
    }
351

352
    protected function createConstructorArgument($parameterData, string $key, \ReflectionParameter $constructorParameter, array &$context, string $format = null): mixed
353
    {
354
        return $this->createAndValidateAttributeValue($constructorParameter->name, $parameterData, $format, $context);
×
355
    }
356

357
    /**
358
     * {@inheritdoc}
359
     *
360
     * Unused in this context.
361
     *
362
     * @return string[]
363
     */
364
    protected function extractAttributes($object, $format = null, array $context = []): array
365
    {
366
        return [];
×
367
    }
368

369
    /**
370
     * {@inheritdoc}
371
     */
372
    protected function getAllowedAttributes(string|object $classOrObject, array $context, bool $attributesAsString = false): array|bool
373
    {
374
        if (!$this->resourceClassResolver->isResourceClass($context['resource_class'])) {
98✔
375
            return parent::getAllowedAttributes($classOrObject, $context, $attributesAsString);
2✔
376
        }
377

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

382
        $allowedAttributes = [];
96✔
383
        foreach ($propertyNames as $propertyName) {
96✔
384
            $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $propertyName, $options);
96✔
385

386
            if (
387
                $this->isAllowedAttribute($classOrObject, $propertyName, null, $context)
96✔
388
                && (
389
                    isset($context['api_normalize']) && $propertyMetadata->isReadable()
96✔
390
                    || isset($context['api_denormalize']) && ($propertyMetadata->isWritable() || !\is_object($classOrObject) && $propertyMetadata->isInitializable())
96✔
391
                )
392
            ) {
393
                $allowedAttributes[] = $propertyName;
96✔
394
            }
395
        }
396

397
        return $allowedAttributes;
96✔
398
    }
399

400
    /**
401
     * {@inheritdoc}
402
     */
403
    protected function isAllowedAttribute(object|string $classOrObject, string $attribute, string $format = null, array $context = []): bool
404
    {
405
        if (!parent::isAllowedAttribute($classOrObject, $attribute, $format, $context)) {
98✔
406
            return false;
2✔
407
        }
408

409
        return $this->canAccessAttribute(\is_object($classOrObject) ? $classOrObject : null, $attribute, $context);
98✔
410
    }
411

412
    /**
413
     * Check if access to the attribute is granted.
414
     */
415
    protected function canAccessAttribute(?object $object, string $attribute, array $context = []): bool
416
    {
417
        if (!$this->resourceClassResolver->isResourceClass($context['resource_class'])) {
98✔
418
            return true;
2✔
419
        }
420

421
        $options = $this->getFactoryOptions($context);
96✔
422
        $propertyMetadata = $this->propertyMetadataFactory->create($context['resource_class'], $attribute, $options);
96✔
423
        $security = $propertyMetadata->getSecurity();
96✔
424
        if (null !== $this->resourceAccessChecker && $security) {
96✔
425
            return $this->resourceAccessChecker->isGranted($context['resource_class'], $security, [
8✔
426
                'object' => $object,
8✔
427
            ]);
8✔
428
        }
429

430
        return true;
96✔
431
    }
432

433
    /**
434
     * Check if access to the attribute is granted.
435
     */
436
    protected function canAccessAttributePostDenormalize(?object $object, ?object $previousObject, string $attribute, array $context = []): bool
437
    {
438
        $options = $this->getFactoryOptions($context);
44✔
439
        $propertyMetadata = $this->propertyMetadataFactory->create($context['resource_class'], $attribute, $options);
44✔
440
        $security = $propertyMetadata->getSecurityPostDenormalize();
44✔
441
        if ($this->resourceAccessChecker && $security) {
44✔
442
            return $this->resourceAccessChecker->isGranted($context['resource_class'], $security, [
4✔
443
                'object' => $object,
4✔
444
                'previous_object' => $previousObject,
4✔
445
            ]);
4✔
446
        }
447

448
        return true;
44✔
449
    }
450

451
    /**
452
     * {@inheritdoc}
453
     */
454
    protected function setAttributeValue(object $object, string $attribute, mixed $value, string $format = null, array $context = []): void
455
    {
456
        try {
457
            $this->setValue($object, $attribute, $this->createAttributeValue($attribute, $value, $format, $context));
60✔
458
        } catch (NotNormalizableValueException $exception) {
14✔
459
            // Only throw if collecting denormalization errors is disabled.
460
            if (!isset($context['not_normalizable_value_exceptions'])) {
10✔
461
                throw $exception;
10✔
462
            }
463
        }
464
    }
465

466
    /**
467
     * Validates the type of the value. Allows using integers as floats for JSON formats.
468
     *
469
     * @throws NotNormalizableValueException
470
     */
471
    protected function validateType(string $attribute, Type $type, mixed $value, string $format = null, array $context = []): void
472
    {
473
        $builtinType = $type->getBuiltinType();
30✔
474
        if (Type::BUILTIN_TYPE_FLOAT === $builtinType && null !== $format && str_contains($format, 'json')) {
30✔
475
            $isValid = \is_float($value) || \is_int($value);
2✔
476
        } else {
477
            $isValid = \call_user_func('is_'.$builtinType, $value);
28✔
478
        }
479

480
        if (!$isValid) {
30✔
481
            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✔
482
        }
483
    }
484

485
    /**
486
     * Denormalizes a collection of objects.
487
     *
488
     * @throws NotNormalizableValueException
489
     */
490
    protected function denormalizeCollection(string $attribute, ApiProperty $propertyMetadata, Type $type, string $className, mixed $value, ?string $format, array $context): array
491
    {
492
        if (!\is_array($value)) {
14✔
493
            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✔
494
        }
495

496
        $collectionKeyType = $type->getCollectionKeyTypes()[0] ?? null;
12✔
497
        $collectionKeyBuiltinType = $collectionKeyType?->getBuiltinType();
12✔
498
        $childContext = $this->createChildContext(['resource_class' => $className] + $context, $attribute, $format);
12✔
499
        unset($childContext['uri_variables']);
12✔
500
        if ($this->resourceMetadataCollectionFactory) {
12✔
501
            $childContext['operation'] = $this->resourceMetadataCollectionFactory->create($className)->getOperation();
2✔
502
        }
503

504
        $values = [];
12✔
505
        foreach ($value as $index => $obj) {
12✔
506
            if (null !== $collectionKeyBuiltinType && !\call_user_func('is_'.$collectionKeyBuiltinType, $index)) {
12✔
507
                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✔
508
            }
509

510
            $values[$index] = $this->denormalizeRelation($attribute, $propertyMetadata, $className, $obj, $format, $childContext);
8✔
511
        }
512

513
        return $values;
8✔
514
    }
515

516
    /**
517
     * Denormalizes a relation.
518
     *
519
     * @throws LogicException
520
     * @throws UnexpectedValueException
521
     * @throws NotNormalizableValueException
522
     */
523
    protected function denormalizeRelation(string $attributeName, ApiProperty $propertyMetadata, string $className, mixed $value, ?string $format, array $context): ?object
524
    {
525
        if (\is_string($value)) {
10✔
526
            try {
527
                return $this->iriConverter->getResourceFromIri($value, $context + ['fetch_data' => true]);
2✔
528
            } catch (ItemNotFoundException $e) {
×
529
                throw new UnexpectedValueException($e->getMessage(), $e->getCode(), $e);
×
530
            } catch (InvalidArgumentException $e) {
×
531
                throw new UnexpectedValueException(sprintf('Invalid IRI "%s".', $value), $e->getCode(), $e);
×
532
            }
533
        }
534

535
        if ($propertyMetadata->isWritableLink()) {
8✔
536
            $context['api_allow_update'] = true;
4✔
537

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

542
            $item = $this->serializer->denormalize($value, $className, $format, $context);
4✔
543
            if (!\is_object($item) && null !== $item) {
4✔
544
                throw new \UnexpectedValueException('Expected item to be an object or null.');
×
545
            }
546

547
            return $item;
4✔
548
        }
549

550
        if (!\is_array($value)) {
4✔
551
            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✔
552
        }
553

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

557
    /**
558
     * Gets the options for the property name collection / property metadata factories.
559
     */
560
    protected function getFactoryOptions(array $context): array
561
    {
562
        $options = [];
98✔
563
        if (isset($context[self::GROUPS])) {
98✔
564
            /* @see https://github.com/symfony/symfony/blob/v4.2.6/src/Symfony/Component/PropertyInfo/Extractor/SerializerExtractor.php */
565
            $options['serializer_groups'] = (array) $context[self::GROUPS];
2✔
566
        }
567

568
        $operationCacheKey = ($context['resource_class'] ?? '').($context['operation_name'] ?? '').($context['api_normalize'] ?? '');
98✔
569
        if ($operationCacheKey && isset($this->localFactoryOptionsCache[$operationCacheKey])) {
98✔
570
            return $options + $this->localFactoryOptionsCache[$operationCacheKey];
98✔
571
        }
572

573
        // This is a hot spot
574
        if (isset($context['resource_class'])) {
98✔
575
            // Note that the groups need to be read on the root operation
576
            $operation = $context['root_operation'] ?? $context['operation'] ?? null;
98✔
577

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

583
            if ($operation) {
98✔
584
                $options['normalization_groups'] = $operation->getNormalizationContext()['groups'] ?? null;
24✔
585
                $options['denormalization_groups'] = $operation->getDenormalizationContext()['groups'] ?? null;
24✔
586
                $options['operation_name'] = $operation->getName();
24✔
587
            }
588
        }
589

590
        return $options + $this->localFactoryOptionsCache[$operationCacheKey] = $options;
98✔
591
    }
592

593
    /**
594
     * {@inheritdoc}
595
     *
596
     * @throws UnexpectedValueException
597
     */
598
    protected function getAttributeValue(object $object, string $attribute, string $format = null, array $context = []): mixed
599
    {
600
        $context['api_attribute'] = $attribute;
44✔
601
        $propertyMetadata = $this->propertyMetadataFactory->create($context['resource_class'], $attribute, $this->getFactoryOptions($context));
44✔
602

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

605
        if ($context['api_denormalize'] ?? false) {
42✔
606
            return $attributeValue;
×
607
        }
608

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

611
        if (
612
            $type
42✔
613
            && $type->isCollection()
42✔
614
            && ($collectionValueType = $type->getCollectionValueTypes()[0] ?? null)
42✔
615
            && ($className = $collectionValueType->getClassName())
42✔
616
            && $this->resourceClassResolver->isResourceClass($className)
42✔
617
        ) {
618
            if (!is_iterable($attributeValue)) {
14✔
619
                throw new UnexpectedValueException('Unexpected non-iterable value for to-many relation.');
×
620
            }
621

622
            $resourceClass = $this->resourceClassResolver->getResourceClass($attributeValue, $className);
14✔
623
            $childContext = $this->createChildContext($context, $attribute, $format);
14✔
624
            unset($childContext['iri'], $childContext['uri_variables'], $childContext['resource_class'], $childContext['operation']);
14✔
625

626
            return $this->normalizeCollectionOfRelations($propertyMetadata, $attributeValue, $resourceClass, $format, $childContext);
14✔
627
        }
628

629
        if (
630
            $type
40✔
631
            && ($className = $type->getClassName())
40✔
632
            && $this->resourceClassResolver->isResourceClass($className)
40✔
633
        ) {
634
            if (!\is_object($attributeValue) && null !== $attributeValue) {
16✔
635
                throw new UnexpectedValueException('Unexpected non-object value for to-one relation.');
×
636
            }
637

638
            $resourceClass = $this->resourceClassResolver->getResourceClass($attributeValue, $className);
16✔
639
            $childContext = $this->createChildContext($context, $attribute, $format);
16✔
640
            $childContext['resource_class'] = $resourceClass;
16✔
641
            if ($this->resourceMetadataCollectionFactory) {
16✔
642
                $childContext['operation'] = $this->resourceMetadataCollectionFactory->create($resourceClass)->getOperation();
6✔
643
            }
644
            unset($childContext['iri'], $childContext['uri_variables']);
16✔
645

646
            return $this->normalizeRelation($propertyMetadata, $attributeValue, $resourceClass, $format, $childContext);
16✔
647
        }
648

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

653
        unset($context['resource_class']);
38✔
654
        unset($context['force_resource_class']);
38✔
655

656
        if ($type && $type->getClassName()) {
38✔
657
            $childContext = $this->createChildContext($context, $attribute, $format);
6✔
658
            unset($childContext['iri'], $childContext['uri_variables']);
6✔
659
            $childContext['output']['gen_id'] = $propertyMetadata->getGenId() ?? true;
6✔
660

661
            return $this->serializer->normalize($attributeValue, $format, $childContext);
6✔
662
        }
663

664
        if ($type && 'array' === $type->getBuiltinType()) {
38✔
665
            $childContext = $this->createChildContext($context, $attribute, $format);
8✔
666
            unset($childContext['iri'], $childContext['uri_variables']);
8✔
667

668
            return $this->serializer->normalize($attributeValue, $format, $childContext);
8✔
669
        }
670

671
        return $this->serializer->normalize($attributeValue, $format, $context);
38✔
672
    }
673

674
    /**
675
     * Normalizes a collection of relations (to-many).
676
     *
677
     * @throws UnexpectedValueException
678
     */
679
    protected function normalizeCollectionOfRelations(ApiProperty $propertyMetadata, iterable $attributeValue, string $resourceClass, ?string $format, array $context): array
680
    {
681
        $value = [];
14✔
682
        foreach ($attributeValue as $index => $obj) {
14✔
683
            if (!\is_object($obj) && null !== $obj) {
8✔
684
                throw new UnexpectedValueException('Unexpected non-object element in to-many relation.');
2✔
685
            }
686

687
            // update context, if concrete object class deviates from general relation class (e.g. in case of polymorphic resources)
688
            $objResourceClass = $this->resourceClassResolver->getResourceClass($obj, $resourceClass);
8✔
689
            $context['resource_class'] = $objResourceClass;
8✔
690
            if ($this->resourceMetadataCollectionFactory) {
8✔
691
                $context['operation'] = $this->resourceMetadataCollectionFactory->create($objResourceClass)->getOperation();
2✔
692
            }
693

694
            $value[$index] = $this->normalizeRelation($propertyMetadata, $obj, $resourceClass, $format, $context);
8✔
695
        }
696

697
        return $value;
12✔
698
    }
699

700
    /**
701
     * Normalizes a relation.
702
     *
703
     * @throws LogicException
704
     * @throws UnexpectedValueException
705
     */
706
    protected function normalizeRelation(ApiProperty $propertyMetadata, ?object $relatedObject, string $resourceClass, ?string $format, array $context): \ArrayObject|array|string|null
707
    {
708
        if (null === $relatedObject || !empty($context['attributes']) || $propertyMetadata->isReadableLink()) {
20✔
709
            if (!$this->serializer instanceof NormalizerInterface) {
14✔
710
                throw new LogicException(sprintf('The injected serializer must be an instance of "%s".', NormalizerInterface::class));
×
711
            }
712

713
            $relatedContext = $context;
14✔
714
            unset($relatedContext['force_resource_class']);
14✔
715
            $normalizedRelatedObject = $this->serializer->normalize($relatedObject, $format, $relatedContext);
14✔
716
            if (!\is_string($normalizedRelatedObject) && !\is_array($normalizedRelatedObject) && !$normalizedRelatedObject instanceof \ArrayObject && null !== $normalizedRelatedObject) {
14✔
717
                throw new UnexpectedValueException('Expected normalized relation to be an IRI, array, \ArrayObject or null');
×
718
            }
719

720
            return $normalizedRelatedObject;
14✔
721
        }
722

723
        $iri = $this->iriConverter->getIriFromResource($relatedObject);
6✔
724

725
        if (isset($context['resources'])) {
6✔
726
            $context['resources'][$iri] = $iri;
2✔
727
        }
728

729
        $push = $propertyMetadata->getPush() ?? false;
6✔
730
        if (isset($context['resources_to_push']) && $push) {
6✔
731
            $context['resources_to_push'][$iri] = $iri;
×
732
        }
733

734
        return $iri;
6✔
735
    }
736

737
    private function createAttributeValue(string $attribute, mixed $value, string $format = null, array &$context = []): mixed
738
    {
739
        try {
740
            return $this->createAndValidateAttributeValue($attribute, $value, $format, $context);
60✔
741
        } catch (NotNormalizableValueException $exception) {
14✔
742
            if (!isset($context['not_normalizable_value_exceptions'])) {
10✔
743
                throw $exception;
10✔
744
            }
745
            $context['not_normalizable_value_exceptions'][] = $exception;
×
746

747
            throw $exception;
×
748
        }
749
    }
750

751
    private function createAndValidateAttributeValue(string $attribute, mixed $value, string $format = null, array $context = []): mixed
752
    {
753
        $propertyMetadata = $this->propertyMetadataFactory->create($context['resource_class'], $attribute, $this->getFactoryOptions($context));
60✔
754
        $type = $propertyMetadata->getBuiltinTypes()[0] ?? null;
60✔
755

756
        if (null === $type) {
60✔
757
            // No type provided, blindly return the value
758
            return $value;
10✔
759
        }
760

761
        if (null === $value && $type->isNullable() || ($context[static::DISABLE_TYPE_ENFORCEMENT] ?? false)) {
50✔
762
            return $value;
6✔
763
        }
764

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

767
        /* From @see AbstractObjectNormalizer::validateAndDenormalize() */
768
        // Fix a collection that contains the only one element
769
        // This is special to xml format only
770
        if ('xml' === $format && null !== $collectionValueType && (!\is_array($value) || !\is_int(key($value)))) {
44✔
771
            $value = [$value];
2✔
772
        }
773

774
        if (
775
            $type->isCollection()
44✔
776
            && null !== $collectionValueType
44✔
777
            && null !== ($className = $collectionValueType->getClassName())
44✔
778
            && $this->resourceClassResolver->isResourceClass($className)
44✔
779
        ) {
780
            $resourceClass = $this->resourceClassResolver->getResourceClass(null, $className);
14✔
781

782
            return $this->denormalizeCollection($attribute, $propertyMetadata, $type, $resourceClass, $value, $format, $context);
14✔
783
        }
784

785
        if (
786
            null !== ($className = $type->getClassName())
36✔
787
            && $this->resourceClassResolver->isResourceClass($className)
36✔
788
        ) {
789
            $resourceClass = $this->resourceClassResolver->getResourceClass(null, $className);
12✔
790
            $childContext = $this->createChildContext($context, $attribute, $format);
12✔
791
            $childContext['resource_class'] = $resourceClass;
12✔
792
            unset($childContext['uri_variables']);
12✔
793
            if ($this->resourceMetadataCollectionFactory) {
12✔
794
                $childContext['operation'] = $this->resourceMetadataCollectionFactory->create($resourceClass)->getOperation();
2✔
795
            }
796

797
            return $this->denormalizeRelation($attribute, $propertyMetadata, $resourceClass, $value, $format, $childContext);
12✔
798
        }
799

800
        if (
801
            $type->isCollection()
30✔
802
            && null !== $collectionValueType
30✔
803
            && null !== ($className = $collectionValueType->getClassName())
30✔
804
        ) {
805
            if (!$this->serializer instanceof DenormalizerInterface) {
×
806
                throw new LogicException(sprintf('The injected serializer must be an instance of "%s".', DenormalizerInterface::class));
×
807
            }
808

809
            unset($context['resource_class']);
×
810

811
            return $this->serializer->denormalize($value, $className.'[]', $format, $context);
×
812
        }
813

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

819
            unset($context['resource_class']);
×
820

821
            return $this->serializer->denormalize($value, $className, $format, $context);
×
822
        }
823

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

833
            switch ($type->getBuiltinType()) {
2✔
834
                case Type::BUILTIN_TYPE_BOOL:
835
                    // according to http://www.w3.org/TR/xmlschema-2/#boolean, valid representations are "false", "true", "0" and "1"
836
                    if ('false' === $value || '0' === $value) {
2✔
837
                        $value = false;
2✔
838
                    } elseif ('true' === $value || '1' === $value) {
2✔
839
                        $value = true;
2✔
840
                    } else {
841
                        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);
×
842
                    }
843
                    break;
2✔
844
                case Type::BUILTIN_TYPE_INT:
845
                    if (ctype_digit($value) || ('-' === $value[0] && ctype_digit(substr($value, 1)))) {
2✔
846
                        $value = (int) $value;
2✔
847
                    } else {
848
                        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);
×
849
                    }
850
                    break;
2✔
851
                case Type::BUILTIN_TYPE_FLOAT:
852
                    if (is_numeric($value)) {
2✔
853
                        return (float) $value;
2✔
854
                    }
855

856
                    return match ($value) {
2✔
857
                        'NaN' => \NAN,
2✔
858
                        'INF' => \INF,
2✔
859
                        '-INF' => -\INF,
2✔
860
                        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✔
861
                    };
2✔
862
            }
863
        }
864

865
        if ($context[static::DISABLE_TYPE_ENFORCEMENT] ?? false) { // @phpstan-ignore-line
30✔
866
            return $value;
×
867
        }
868

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

871
        return $value;
28✔
872
    }
873

874
    /**
875
     * Sets a value of the object using the PropertyAccess component.
876
     */
877
    private function setValue(object $object, string $attributeName, mixed $value): void
878
    {
879
        try {
880
            $this->propertyAccessor->setValue($object, $attributeName, $value);
46✔
881
        } catch (NoSuchPropertyException) {
2✔
882
            // Properties not found are ignored
883
        }
884
    }
885
}
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