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

api-platform / core / 6054263056

01 Sep 2023 09:47PM UTC coverage: 58.794% (-0.09%) from 58.879%
6054263056

push

github

web-flow
fix(serializer): retrieve only first uriVariable from operation (#5788)

* fix(serializer): retrieve only first uriVariable from operation

* array default

---------

Co-authored-by: Antoine Bluchet <soyuka@users.noreply.github.com>

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

10861 of 18473 relevant lines covered (58.79%)

11.3 hits per line

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

73.6
/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
    use OperationContextTrait;
59

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

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

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

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

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

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

92
    public function getSupportedTypes(?string $format): array
93
    {
94
        return [
36✔
95
            'object' => true,
36✔
96
        ];
36✔
97
    }
98

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

113
        return true;
×
114
    }
115

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

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

134
            return $this->serializer->normalize($object, $format, $context);
2✔
135
        }
136

137
        // Never remove this, with `application/json` we don't use our AbstractCollectionNormalizer and we need
138
        // to remove the collection operation from our context or we'll introduce security issues
139
        if (isset($context['operation']) && $context['operation'] instanceof CollectionOperationInterface) {
48✔
140
            unset($context['operation_name']);
×
141
            unset($context['operation']);
×
142
            unset($context['iri']);
×
143
        }
144

145
        if ($this->resourceClassResolver->isResourceClass($resourceClass)) {
48✔
146
            $context = $this->initContext($resourceClass, $context);
46✔
147
        }
148

149
        $context['api_normalize'] = true;
48✔
150
        $iri = $context['iri'] ??= $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_URL, $context['operation'] ?? null, $context);
48✔
151

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

165
        if (isset($context['resources'])) {
48✔
166
            $context['resources'][$iri] = $iri;
34✔
167
        }
168

169
        $data = parent::normalize($object, $format, $context);
48✔
170

171
        if ($emptyResourceAsIri && \is_array($data) && 0 === \count($data)) {
46✔
172
            return $iri;
×
173
        }
174

175
        return $data;
46✔
176
    }
177

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

187
        return $this->localCache[$type] ?? $this->localCache[$type] = $this->resourceClassResolver->isResourceClass($type);
12✔
188
    }
189

190
    /**
191
     * {@inheritdoc}
192
     */
193
    public function denormalize(mixed $data, string $class, string $format = null, array $context = []): mixed
194
    {
195
        $resourceClass = $class;
58✔
196

197
        if ($inputClass = $this->getInputClass($context)) {
58✔
198
            if (!$this->serializer instanceof DenormalizerInterface) {
×
199
                throw new LogicException('Cannot denormalize the input because the injected serializer is not a denormalizer');
×
200
            }
201

202
            unset($context['input'], $context['operation'], $context['operation_name']);
×
203
            $context['resource_class'] = $inputClass;
×
204

205
            try {
206
                return $this->serializer->denormalize($data, $inputClass, $format, $context);
×
207
            } catch (NotNormalizableValueException $e) {
×
208
                throw new UnexpectedValueException('The input data is misformatted.', $e->getCode(), $e);
×
209
            }
210
        }
211

212
        if (null === $objectToPopulate = $this->extractObjectToPopulate($resourceClass, $context, static::OBJECT_TO_POPULATE)) {
58✔
213
            $normalizedData = \is_scalar($data) ? [$data] : $this->prepareForDenormalization($data);
50✔
214
            $class = $this->getClassDiscriminatorResolvedClass($normalizedData, $class, $context);
50✔
215
        }
216

217
        $context['api_denormalize'] = true;
58✔
218

219
        if ($this->resourceClassResolver->isResourceClass($class)) {
58✔
220
            $resourceClass = $this->resourceClassResolver->getResourceClass($objectToPopulate, $class);
58✔
221
            $context['resource_class'] = $resourceClass;
58✔
222
        }
223

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

234
        if (!\is_array($data)) {
58✔
235
            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);
×
236
        }
237

238
        $previousObject = $this->clone($objectToPopulate);
58✔
239
        $object = parent::denormalize($data, $class, $format, $context);
58✔
240

241
        if (!$this->resourceClassResolver->isResourceClass($class)) {
44✔
242
            return $object;
×
243
        }
244

245
        // Bypass the post-denormalize attribute revert logic if the object could not be
246
        // cloned since we cannot possibly revert any changes made to it.
247
        if (null !== $objectToPopulate && null === $previousObject) {
44✔
248
            return $object;
2✔
249
        }
250

251
        $options = $this->getFactoryOptions($context);
42✔
252
        $propertyNames = iterator_to_array($this->propertyNameCollectionFactory->create($resourceClass, $options));
42✔
253

254
        // Revert attributes that aren't allowed to be changed after a post-denormalize check
255
        foreach (array_keys($data) as $attribute) {
42✔
256
            $attribute = $this->nameConverter ? $this->nameConverter->denormalize((string) $attribute) : $attribute;
42✔
257
            if (!\in_array($attribute, $propertyNames, true)) {
42✔
258
                continue;
×
259
            }
260

261
            if (!$this->canAccessAttributePostDenormalize($object, $previousObject, $attribute, $context)) {
42✔
262
                if (null !== $previousObject) {
4✔
263
                    $this->setValue($object, $attribute, $this->propertyAccessor->getValue($previousObject, $attribute));
2✔
264
                } else {
265
                    $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $attribute, $options);
2✔
266
                    $this->setValue($object, $attribute, $propertyMetadata->getDefault());
2✔
267
                }
268
            }
269
        }
270

271
        return $object;
42✔
272
    }
273

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

287
            return $object;
8✔
288
        }
289

290
        $class = $this->getClassDiscriminatorResolvedClass($data, $class, $context);
50✔
291
        $reflectionClass = new \ReflectionClass($class);
50✔
292

293
        $constructor = $this->getConstructor($data, $class, $context, $reflectionClass, $allowedAttributes);
50✔
294
        if ($constructor) {
50✔
295
            $constructorParameters = $constructor->getParameters();
46✔
296

297
            $params = [];
46✔
298
            foreach ($constructorParameters as $constructorParameter) {
46✔
299
                $paramName = $constructorParameter->name;
×
300
                $key = $this->nameConverter ? $this->nameConverter->normalize($paramName, $class, $format, $context) : $paramName;
×
301

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

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

324
                    // Don't run set for a parameter passed to the constructor
325
                    unset($data[$key]);
×
326
                } elseif (isset($context[static::DEFAULT_CONSTRUCTOR_ARGUMENTS][$class][$key])) {
×
327
                    $params[] = $context[static::DEFAULT_CONSTRUCTOR_ARGUMENTS][$class][$key];
×
328
                } elseif ($constructorParameter->isDefaultValueAvailable()) {
×
329
                    $params[] = $constructorParameter->getDefaultValue();
×
330
                } else {
331
                    if (!isset($context['not_normalizable_value_exceptions'])) {
×
332
                        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]);
×
333
                    }
334

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

340
            if (\count($context['not_normalizable_value_exceptions'] ?? []) > 0) {
46✔
341
                return $reflectionClass->newInstanceWithoutConstructor();
×
342
            }
343

344
            if ($constructor->isConstructor()) {
46✔
345
                return $reflectionClass->newInstanceArgs($params);
46✔
346
            }
347

348
            return $constructor->invokeArgs(null, $params);
×
349
        }
350

351
        return new $class();
4✔
352
    }
353

354
    protected function getClassDiscriminatorResolvedClass(array $data, string $class, array $context = []): string
355
    {
356
        if (null === $this->classDiscriminatorResolver || (null === $mapping = $this->classDiscriminatorResolver->getMappingForClass($class))) {
50✔
357
            return $class;
50✔
358
        }
359

360
        if (!isset($data[$mapping->getTypeProperty()])) {
×
361
            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());
×
362
        }
363

364
        $type = $data[$mapping->getTypeProperty()];
×
365
        if (null === ($mappedClass = $mapping->getClassForType($type))) {
×
366
            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);
×
367
        }
368

369
        return $mappedClass;
×
370
    }
371

372
    protected function createConstructorArgument($parameterData, string $key, \ReflectionParameter $constructorParameter, array &$context, string $format = null): mixed
373
    {
374
        return $this->createAndValidateAttributeValue($constructorParameter->name, $parameterData, $format, $context);
×
375
    }
376

377
    /**
378
     * {@inheritdoc}
379
     *
380
     * Unused in this context.
381
     *
382
     * @return string[]
383
     */
384
    protected function extractAttributes($object, $format = null, array $context = []): array
385
    {
386
        return [];
×
387
    }
388

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

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

402
        $allowedAttributes = [];
96✔
403
        foreach ($propertyNames as $propertyName) {
96✔
404
            $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $propertyName, $options);
96✔
405

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

417
        return $allowedAttributes;
96✔
418
    }
419

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

429
        return $this->canAccessAttribute(\is_object($classOrObject) ? $classOrObject : null, $attribute, $context);
98✔
430
    }
431

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

441
        $options = $this->getFactoryOptions($context);
96✔
442
        $propertyMetadata = $this->propertyMetadataFactory->create($context['resource_class'], $attribute, $options);
96✔
443
        $security = $propertyMetadata->getSecurity();
96✔
444
        if (null !== $this->resourceAccessChecker && $security) {
96✔
445
            return $this->resourceAccessChecker->isGranted($context['resource_class'], $security, [
10✔
446
                'object' => $object,
10✔
447
            ]);
10✔
448
        }
449

450
        return true;
96✔
451
    }
452

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

468
        return true;
42✔
469
    }
470

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

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

500
        if (!$isValid) {
30✔
501
            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✔
502
        }
503
    }
504

505
    /**
506
     * Denormalizes a collection of objects.
507
     *
508
     * @throws NotNormalizableValueException
509
     */
510
    protected function denormalizeCollection(string $attribute, ApiProperty $propertyMetadata, Type $type, string $className, mixed $value, ?string $format, array $context): array
511
    {
512
        if (!\is_array($value)) {
14✔
513
            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✔
514
        }
515

516
        $collectionKeyType = $type->getCollectionKeyTypes()[0] ?? null;
12✔
517
        $collectionKeyBuiltinType = $collectionKeyType?->getBuiltinType();
12✔
518
        $childContext = $this->createChildContext($this->createOperationContext($context, $className), $attribute, $format);
12✔
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
            if ($operation = ($context['root_operation'] ?? null)) {
98✔
592
                $options['normalization_groups'] = $operation->getNormalizationContext()['groups'] ?? null;
4✔
593
                $options['denormalization_groups'] = $operation->getDenormalizationContext()['groups'] ?? null;
4✔
594
                $options['operation_name'] = $operation->getName();
4✔
595
            }
596
        }
597

598
        return $options + $this->localFactoryOptionsCache[$operationCacheKey] = $options;
98✔
599
    }
600

601
    /**
602
     * {@inheritdoc}
603
     *
604
     * @throws UnexpectedValueException
605
     */
606
    protected function getAttributeValue(object $object, string $attribute, string $format = null, array $context = []): mixed
607
    {
608
        $context['api_attribute'] = $attribute;
46✔
609
        $propertyMetadata = $this->propertyMetadataFactory->create($context['resource_class'], $attribute, $this->getFactoryOptions($context));
46✔
610

611
        $attributeValue = $this->propertyAccessor->getValue($object, $attribute);
46✔
612

613
        if ($context['api_denormalize'] ?? false) {
44✔
614
            return $attributeValue;
×
615
        }
616

617
        $type = $propertyMetadata->getBuiltinTypes()[0] ?? null;
44✔
618

619
        if (
620
            $type
44✔
621
            && $type->isCollection()
44✔
622
            && ($collectionValueType = $type->getCollectionValueTypes()[0] ?? null)
44✔
623
            && ($className = $collectionValueType->getClassName())
44✔
624
            && $this->resourceClassResolver->isResourceClass($className)
44✔
625
        ) {
626
            if (!is_iterable($attributeValue)) {
14✔
627
                throw new UnexpectedValueException('Unexpected non-iterable value for to-many relation.');
×
628
            }
629

630
            $resourceClass = $this->resourceClassResolver->getResourceClass($attributeValue, $className);
14✔
631
            $childContext = $this->createChildContext($this->createOperationContext($context, $resourceClass), $attribute, $format);
14✔
632

633
            return $this->normalizeCollectionOfRelations($propertyMetadata, $attributeValue, $resourceClass, $format, $childContext);
14✔
634
        }
635

636
        if (
637
            $type
42✔
638
            && ($className = $type->getClassName())
42✔
639
            && $this->resourceClassResolver->isResourceClass($className)
42✔
640
        ) {
641
            if (!\is_object($attributeValue) && null !== $attributeValue) {
16✔
642
                throw new UnexpectedValueException('Unexpected non-object value for to-one relation.');
×
643
            }
644

645
            $resourceClass = $this->resourceClassResolver->getResourceClass($attributeValue, $className);
16✔
646
            $childContext = $this->createChildContext($this->createOperationContext($context, $resourceClass), $attribute, $format);
16✔
647

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

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

655
        unset($context['resource_class']);
40✔
656
        unset($context['force_resource_class']);
40✔
657

658
        // Anonymous resources
659
        if ($type && $type->getClassName()) {
40✔
660
            $childContext = $this->createChildContext($context, $attribute, $format);
6✔
661
            $childContext['output']['gen_id'] = $propertyMetadata->getGenId() ?? true;
6✔
662

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

666
        if ($type && 'array' === $type->getBuiltinType()) {
40✔
667
            $childContext = $this->createChildContext($context, $attribute, $format);
8✔
668

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

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

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

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

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

698
        return $value;
14✔
699
    }
700

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

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

720
            return $normalizedRelatedObject;
12✔
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);
58✔
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));
58✔
754
        $type = $propertyMetadata->getBuiltinTypes()[0] ?? null;
58✔
755

756
        if (null === $type) {
58✔
757
            // No type provided, blindly return the value
758
            return $value;
8✔
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($this->createOperationContext($context, $resourceClass), $attribute, $format);
12✔
791

792
            return $this->denormalizeRelation($attribute, $propertyMetadata, $resourceClass, $value, $format, $childContext);
12✔
793
        }
794

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

804
            unset($context['resource_class']);
×
805

806
            return $this->serializer->denormalize($value, $className.'[]', $format, $context);
×
807
        }
808

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

814
            unset($context['resource_class']);
×
815

816
            return $this->serializer->denormalize($value, $className, $format, $context);
×
817
        }
818

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

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

851
                    return match ($value) {
2✔
852
                        'NaN' => \NAN,
2✔
853
                        'INF' => \INF,
2✔
854
                        '-INF' => -\INF,
2✔
855
                        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✔
856
                    };
2✔
857
            }
858
        }
859

860
        if ($context[static::DISABLE_TYPE_ENFORCEMENT] ?? false) { // @phpstan-ignore-line
30✔
861
            return $value;
×
862
        }
863

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

866
        return $value;
28✔
867
    }
868

869
    /**
870
     * Sets a value of the object using the PropertyAccess component.
871
     */
872
    private function setValue(object $object, string $attributeName, mixed $value): void
873
    {
874
        try {
875
            $this->propertyAccessor->setValue($object, $attributeName, $value);
44✔
876
        } catch (NoSuchPropertyException) {
2✔
877
            // Properties not found are ignored
878
        }
879
    }
880
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc