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

api-platform / core / 15779525458

20 Jun 2025 01:00PM UTC coverage: 22.024% (-0.04%) from 22.065%
15779525458

push

github

web-flow
feat(serializer): ability to throw access denied exception when denormalizing secured properties (#7221)

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

6 of 126 new or added lines in 3 files covered. (4.76%)

125 existing lines in 11 files now uncovered.

11493 of 52185 relevant lines covered (22.02%)

21.67 hits per line

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

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

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

12
declare(strict_types=1);
13

14
namespace ApiPlatform\Serializer;
15

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

176
            return $iri;
×
177
        }
178

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

183
        return $data;
448✔
184
    }
185

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

296
        return $object;
12✔
297
    }
298

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

312
            return $object;
×
313
        }
314

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

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

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

330
                $allowed = false === $allowedAttributes || (\is_array($allowedAttributes) && \in_array($paramName, $allowedAttributes, true));
8✔
331
                $ignored = !$this->isAllowedAttribute($class, $paramName, $format, $context);
8✔
332
                if ($constructorParameter->isVariadic()) {
8✔
333
                    if ($allowed && !$ignored && (isset($data[$key]) || \array_key_exists($key, $data))) {
×
334
                        if (!\is_array($data[$paramName])) {
×
335
                            throw new RuntimeException(\sprintf('Cannot create an instance of %s from serialized data because the variadic parameter %s can only accept an array.', $class, $constructorParameter->name));
×
336
                        }
337

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

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

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

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

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

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

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

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

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

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

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

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

411
        return $mappedClass;
×
412
    }
413

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

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

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

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

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

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

458
        return $allowedAttributes;
436✔
459
    }
460

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

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

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

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

492
        return true;
428✔
493
    }
494

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

511
        return true;
10✔
512
    }
513

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

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

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

547
        if (!$isValid) {
×
548
            throw NotNormalizableValueException::createForUnexpectedDataType(\sprintf('The type of the "%s" attribute must be "%s", "%s" given.', $attribute, $builtinType, \gettype($value)), $value, [$builtinType], $context['deserialization_path'] ?? null);
×
549
        }
550
    }
551

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

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

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

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

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

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

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

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

613
        return $values;
×
614
    }
615

616
    /**
617
     * Denormalizes a collection of objects.
618
     *
619
     * @throws NotNormalizableValueException
620
     */
621
    protected function denormalizeObjectCollection(string $attribute, ApiProperty $propertyMetadata, Type $type, string $className, mixed $value, ?string $format, array $context): array
622
    {
623
        if (!\is_array($value)) {
2✔
624
            throw NotNormalizableValueException::createForUnexpectedDataType(\sprintf('The type of the "%s" attribute must be "array", "%s" given.', $attribute, \gettype($value)), $value, ['array'], $context['deserialization_path'] ?? null);
2✔
625
        }
626

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

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

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

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

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

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

651
        return $values;
×
652
    }
653

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

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

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

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

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

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

693
            return $item;
×
694
        }
695

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

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

703
    /**
704
     * Gets the options for the property name collection / property metadata factories.
705
     */
706
    protected function getFactoryOptions(array $context): array
707
    {
708
        $options = [];
448✔
709
        if (isset($context[self::GROUPS])) {
448✔
710
            /* @see https://github.com/symfony/symfony/blob/v4.2.6/src/Symfony/Component/PropertyInfo/Extractor/SerializerExtractor.php */
711
            $options['serializer_groups'] = (array) $context[self::GROUPS];
158✔
712
        }
713

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

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

730
        return $options + $this->localFactoryOptionsCache[$operationCacheKey.$suffix] = $options;
448✔
731
    }
732

733
    /**
734
     * {@inheritdoc}
735
     *
736
     * @throws UnexpectedValueException
737
     */
738
    protected function getAttributeValue(object $object, string $attribute, ?string $format = null, array $context = []): mixed
739
    {
740
        $context['api_attribute'] = $attribute;
434✔
741
        $context['property_metadata'] = $propertyMetadata = $this->propertyMetadataFactory->create($context['resource_class'], $attribute, $this->getFactoryOptions($context));
434✔
742

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

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

750
            foreach ($types as $type) {
×
751
                if (
752
                    $type->isCollection()
×
753
                    && ($collectionValueType = $type->getCollectionValueTypes()[0] ?? null)
×
754
                    && ($className = $collectionValueType->getClassName())
×
755
                    && $this->resourceClassResolver->isResourceClass($className)
×
756
                ) {
757
                    $childContext = $this->createChildContext($this->createOperationContext($context, $className), $attribute, $format);
×
758

759
                    // @see ApiPlatform\Hal\Serializer\ItemNormalizer:getComponents logic for intentional duplicate content
760
                    // @see ApiPlatform\JsonApi\Serializer\ItemNormalizer:getComponents logic for intentional duplicate content
761
                    if ('jsonld' === $format && $itemUriTemplate = $propertyMetadata->getUriTemplate()) {
×
762
                        $operation = $this->resourceMetadataCollectionFactory->create($className)->getOperation(
×
763
                            operationName: $itemUriTemplate,
×
764
                            forceCollection: true,
×
765
                            httpOperation: true
×
766
                        );
×
767

768
                        return $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_PATH, $operation, $childContext);
×
769
                    }
770

771
                    $attributeValue = $this->propertyAccessor->getValue($object, $attribute);
×
772

773
                    if (!is_iterable($attributeValue)) {
×
774
                        throw new UnexpectedValueException('Unexpected non-iterable value for to-many relation.');
×
775
                    }
776

777
                    $resourceClass = $this->resourceClassResolver->getResourceClass($attributeValue, $className);
×
778

779
                    $data = $this->normalizeCollectionOfRelations($propertyMetadata, $attributeValue, $resourceClass, $format, $childContext);
×
780
                    $context['data'] = $data;
×
781
                    $context['type'] = $type;
×
782

783
                    if ($this->tagCollector) {
×
784
                        $this->tagCollector->collect($context);
×
785
                    }
786

787
                    return $data;
×
788
                }
789

790
                if (
791
                    ($className = $type->getClassName())
×
792
                    && $this->resourceClassResolver->isResourceClass($className)
×
793
                ) {
794
                    $childContext = $this->createChildContext($this->createOperationContext($context, $className), $attribute, $format);
×
795
                    unset($childContext['iri'], $childContext['uri_variables'], $childContext['item_uri_template']);
×
796
                    if ('jsonld' === $format && $uriTemplate = $propertyMetadata->getUriTemplate()) {
×
797
                        $operation = $this->resourceMetadataCollectionFactory->create($className)->getOperation(
×
798
                            operationName: $uriTemplate,
×
799
                            httpOperation: true
×
800
                        );
×
801

802
                        return $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_PATH, $operation, $childContext);
×
803
                    }
804

805
                    $attributeValue = $this->propertyAccessor->getValue($object, $attribute);
×
806

807
                    if (!\is_object($attributeValue) && null !== $attributeValue) {
×
808
                        throw new UnexpectedValueException('Unexpected non-object value for to-one relation.');
×
809
                    }
810

811
                    $resourceClass = $this->resourceClassResolver->getResourceClass($attributeValue, $className);
×
812

813
                    $data = $this->normalizeRelation($propertyMetadata, $attributeValue, $resourceClass, $format, $childContext);
×
814
                    $context['data'] = $data;
×
815
                    $context['type'] = $type;
×
816

817
                    if ($this->tagCollector) {
×
818
                        $this->tagCollector->collect($context);
×
819
                    }
820

821
                    return $data;
×
822
                }
823

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

828
                unset(
×
829
                    $context['resource_class'],
×
830
                    $context['force_resource_class'],
×
831
                    $context['uri_variables'],
×
832
                );
×
833

834
                // Anonymous resources
835
                if ($className) {
×
836
                    $childContext = $this->createChildContext($this->createOperationContext($context, $className), $attribute, $format);
×
837
                    $childContext['output']['gen_id'] = $propertyMetadata->getGenId() ?? true;
×
838

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

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

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

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

852
                    $attributeValue = $this->propertyAccessor->getValue($object, $attribute);
×
853

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

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

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

868
            $attributeValue = $this->propertyAccessor->getValue($object, $attribute);
×
869

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

873
        $type = $propertyMetadata->getNativeType();
434✔
874

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

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

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

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

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

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

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

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

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

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

920
                return $data;
14✔
921
            }
922

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

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

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

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

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

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

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

951
                return $data;
20✔
952
            }
953

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1022
        return $value;
14✔
1023
    }
1024

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

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

1044
            return $normalizedRelatedObject;
14✔
1045
        }
1046

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

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

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

1063
        return $iri;
8✔
1064
    }
1065

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

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

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

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

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

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

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

1113
            $collectionValueType = null;
12✔
1114

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

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

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

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

1147
                        continue;
×
1148
                    }
1149

1150
                    throw $e;
2✔
1151
                }
1152
            }
1153

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

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

1168
                        continue;
2✔
1169
                    }
1170

1171
                    throw $e;
×
1172
                }
1173
            }
1174

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

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

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

1192
                        continue;
×
1193
                    }
1194

1195
                    throw $e;
×
1196
                }
1197
            }
1198

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

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

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

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

1220
                        continue;
2✔
1221
                    }
1222

1223
                    throw $e;
×
1224
                }
1225
            }
1226

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

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

1241
                switch ($typeIdentifier) {
1242
                    case TypeIdentifier::BOOL:
×
1243
                        // according to http://www.w3.org/TR/xmlschema-2/#boolean, valid representations are "false", "true", "0" and "1"
1244
                        if ('false' === $value || '0' === $value) {
×
1245
                            $value = false;
×
1246
                        } elseif ('true' === $value || '1' === $value) {
×
1247
                            $value = true;
×
1248
                        } else {
1249
                            // union/intersect types: try the next type, if not valid, an exception will be thrown at the end
1250
                            if ($isMultipleTypes) {
×
1251
                                break 2;
×
1252
                            }
1253
                            throw NotNormalizableValueException::createForUnexpectedDataType(\sprintf('The type of the "%s" attribute for class "%s" must be bool ("%s" given).', $attribute, $className, $value), $value, ['bool'], $context['deserialization_path'] ?? null);
×
1254
                        }
1255
                        break;
×
1256
                    case TypeIdentifier::INT:
×
1257
                        if (ctype_digit($value) || ('-' === $value[0] && ctype_digit(substr($value, 1)))) {
×
1258
                            $value = (int) $value;
×
1259
                        } else {
1260
                            // union/intersect types: try the next type, if not valid, an exception will be thrown at the end
1261
                            if ($isMultipleTypes) {
×
1262
                                break 2;
×
1263
                            }
1264
                            throw NotNormalizableValueException::createForUnexpectedDataType(\sprintf('The type of the "%s" attribute for class "%s" must be int ("%s" given).', $attribute, $className, $value), $value, ['int'], $context['deserialization_path'] ?? null);
×
1265
                        }
1266
                        break;
×
1267
                    case TypeIdentifier::FLOAT:
×
1268
                        if (is_numeric($value)) {
×
1269
                            return (float) $value;
×
1270
                        }
1271

1272
                        switch ($value) {
1273
                            case 'NaN':
×
1274
                                return \NAN;
×
1275
                            case 'INF':
×
1276
                                return \INF;
×
1277
                            case '-INF':
×
1278
                                return -\INF;
×
1279
                            default:
1280
                                // union/intersect types: try the next type, if not valid, an exception will be thrown at the end
1281
                                if ($isMultipleTypes) {
×
1282
                                    break 3;
×
1283
                                }
1284
                                throw NotNormalizableValueException::createForUnexpectedDataType(\sprintf('The type of the "%s" attribute for class "%s" must be float ("%s" given).', $attribute, $className, $value), $value, ['float'], $context['deserialization_path'] ?? null);
×
1285
                        }
1286
                }
1287
            }
1288

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

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

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

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

1310
        if ($denormalizationException) {
8✔
1311
            if ($type instanceof Type && $type->isSatisfiedBy(static fn ($type) => $type instanceof BuiltinType) && !$type->isSatisfiedBy($typeIsResourceClass)) {
2✔
1312
                throw NotNormalizableValueException::createForUnexpectedDataType(\sprintf('The type of the "%s" attribute must be "%s", "%s" given.', $attribute, $type, \gettype($value)), $value, array_map(strval(...), $types), $context['deserialization_path'] ?? null);
2✔
1313
            }
1314

1315
            throw $denormalizationException;
2✔
1316
        }
1317

1318
        return $value;
6✔
1319
    }
1320

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