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

api-platform / core / 13175753759

06 Feb 2025 09:30AM UTC coverage: 0.0% (-7.7%) from 7.663%
13175753759

Pull #6947

github

web-flow
Merge 432a515ad into de2d298e3
Pull Request #6947: fix(metadata): remove temporary fix for ArrayCollection

0 of 1 new or added line in 1 file covered. (0.0%)

11655 existing lines in 385 files now uncovered.

0 of 47351 relevant lines covered (0.0%)

0.0 hits per line

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

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

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

12
declare(strict_types=1);
13

14
namespace ApiPlatform\Serializer;
15

16
use ApiPlatform\Metadata\ApiProperty;
17
use ApiPlatform\Metadata\CollectionOperationInterface;
18
use ApiPlatform\Metadata\Exception\InvalidArgumentException;
19
use ApiPlatform\Metadata\Exception\ItemNotFoundException;
20
use ApiPlatform\Metadata\IriConverterInterface;
21
use ApiPlatform\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
22
use ApiPlatform\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
23
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
24
use ApiPlatform\Metadata\ResourceAccessCheckerInterface;
25
use ApiPlatform\Metadata\ResourceClassResolverInterface;
26
use ApiPlatform\Metadata\UrlGeneratorInterface;
27
use ApiPlatform\Metadata\Util\ClassInfoTrait;
28
use ApiPlatform\Metadata\Util\CloneTrait;
29
use Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException;
30
use Symfony\Component\PropertyAccess\PropertyAccess;
31
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
32
use Symfony\Component\PropertyInfo\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
    protected ?ResourceAccessCheckerInterface $resourceAccessChecker;
64

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

UNCOV
71
        parent::__construct($classMetadataFactory, $nameConverter, null, null, \Closure::fromCallable($this->getObjectClass(...)), $defaultContext);
×
UNCOV
72
        $this->propertyAccessor = $propertyAccessor ?: PropertyAccess::createPropertyAccessor();
×
UNCOV
73
        $this->resourceAccessChecker = $resourceAccessChecker;
×
UNCOV
74
        $this->resourceMetadataCollectionFactory = $resourceMetadataCollectionFactory;
×
75
    }
76

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

UNCOV
86
        $class = $context['force_resource_class'] ?? $this->getObjectClass($data);
×
UNCOV
87
        if (($context['output']['class'] ?? null) === $class) {
×
UNCOV
88
            return true;
×
89
        }
90

UNCOV
91
        return $this->resourceClassResolver->isResourceClass($class);
×
92
    }
93

94
    public function getSupportedTypes(?string $format): array
95
    {
UNCOV
96
        return [
×
UNCOV
97
            'object' => true,
×
UNCOV
98
        ];
×
99
    }
100

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

UNCOV
114
            unset($context['output'], $context['operation'], $context['operation_name']);
×
UNCOV
115
            $context['resource_class'] = $outputClass;
×
UNCOV
116
            $context['api_sub_level'] = true;
×
UNCOV
117
            $context[self::ALLOW_EXTRA_ATTRIBUTES] = false;
×
118

UNCOV
119
            return $this->serializer->normalize($object, $format, $context);
×
120
        }
121

122
        // Never remove this, with `application/json` we don't use our AbstractCollectionNormalizer and we need
123
        // to remove the collection operation from our context or we'll introduce security issues
UNCOV
124
        if (isset($context['operation']) && $context['operation'] instanceof CollectionOperationInterface) {
×
UNCOV
125
            unset($context['operation_name'], $context['operation'], $context['iri']);
×
126
        }
127

UNCOV
128
        if ($this->resourceClassResolver->isResourceClass($resourceClass)) {
×
UNCOV
129
            $context = $this->initContext($resourceClass, $context);
×
130
        }
131

UNCOV
132
        $context['api_normalize'] = true;
×
UNCOV
133
        $iri = $context['iri'] ??= $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_URL, $context['operation'] ?? null, $context);
×
134

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

UNCOV
148
        if (!$this->tagCollector && isset($context['resources'])) {
×
149
            $context['resources'][$iri] = $iri;
×
150
        }
151

UNCOV
152
        $context['object'] = $object;
×
UNCOV
153
        $context['format'] = $format;
×
154

UNCOV
155
        $data = parent::normalize($object, $format, $context);
×
156

UNCOV
157
        $context['data'] = $data;
×
UNCOV
158
        unset($context['property_metadata'], $context['api_attribute']);
×
159

UNCOV
160
        if ($emptyResourceAsIri && \is_array($data) && 0 === \count($data)) {
×
161
            $context['data'] = $iri;
×
162

163
            if ($this->tagCollector) {
×
164
                $this->tagCollector->collect($context);
×
165
            }
166

167
            return $iri;
×
168
        }
169

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

UNCOV
174
        return $data;
×
175
    }
176

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

UNCOV
186
        return $this->localCache[$type] ?? $this->localCache[$type] = $this->resourceClassResolver->isResourceClass($type);
×
187
    }
188

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

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

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

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

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

UNCOV
216
        $context['api_denormalize'] = true;
×
217

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

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

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

UNCOV
237
        $previousObject = $this->clone($objectToPopulate);
×
UNCOV
238
        $object = parent::denormalize($data, $class, $format, $context);
×
239

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

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

UNCOV
250
        $options = $this->getFactoryOptions($context);
×
UNCOV
251
        $propertyNames = iterator_to_array($this->propertyNameCollectionFactory->create($resourceClass, $options));
×
252

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

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

UNCOV
270
        return $object;
×
271
    }
272

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

UNCOV
286
            return $object;
×
287
        }
288

UNCOV
289
        $class = $this->getClassDiscriminatorResolvedClass($data, $class, $context);
×
UNCOV
290
        $reflectionClass = new \ReflectionClass($class);
×
291

UNCOV
292
        $constructor = $this->getConstructor($data, $class, $context, $reflectionClass, $allowedAttributes);
×
UNCOV
293
        if ($constructor) {
×
UNCOV
294
            $constructorParameters = $constructor->getParameters();
×
295

UNCOV
296
            $params = [];
×
UNCOV
297
            $missingConstructorArguments = [];
×
UNCOV
298
            foreach ($constructorParameters as $constructorParameter) {
×
UNCOV
299
                $paramName = $constructorParameter->name;
×
UNCOV
300
                $key = $this->nameConverter ? $this->nameConverter->normalize($paramName, $class, $format, $context) : $paramName;
×
UNCOV
301
                $attributeContext = $this->getAttributeDenormalizationContext($class, $paramName, $context);
×
UNCOV
302
                $attributeContext['deserialization_path'] = $attributeContext['deserialization_path'] ?? $key;
×
303

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

312
                        $params[] = $data[$paramName];
×
313
                    }
UNCOV
314
                } elseif ($allowed && !$ignored && (isset($data[$key]) || \array_key_exists($key, $data))) {
×
315
                    try {
UNCOV
316
                        $params[] = $this->createConstructorArgument($data[$key], $key, $constructorParameter, $attributeContext, $format);
×
UNCOV
317
                    } catch (NotNormalizableValueException $exception) {
×
UNCOV
318
                        if (!isset($context['not_normalizable_value_exceptions'])) {
×
UNCOV
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
UNCOV
325
                    unset($data[$key]);
×
UNCOV
326
                } elseif (isset($context[static::DEFAULT_CONSTRUCTOR_ARGUMENTS][$class][$key])) {
×
327
                    $params[] = $context[static::DEFAULT_CONSTRUCTOR_ARGUMENTS][$class][$key];
×
UNCOV
328
                } elseif ($constructorParameter->isDefaultValueAvailable()) {
×
UNCOV
329
                    $params[] = $constructorParameter->getDefaultValue();
×
330
                } else {
UNCOV
331
                    if (!isset($context['not_normalizable_value_exceptions'])) {
×
UNCOV
332
                        $missingConstructorArguments[] = $constructorParameter->name;
×
333
                    }
334

UNCOV
335
                    $constructorParameterType = 'unknown';
×
UNCOV
336
                    $reflectionType = $constructorParameter->getType();
×
UNCOV
337
                    if ($reflectionType instanceof \ReflectionNamedType) {
×
UNCOV
338
                        $constructorParameterType = $reflectionType->getName();
×
339
                    }
340

UNCOV
341
                    $exception = NotNormalizableValueException::createForUnexpectedDataType(
×
UNCOV
342
                        \sprintf('Failed to create object because the class misses the "%s" property.', $constructorParameter->name),
×
UNCOV
343
                        null,
×
UNCOV
344
                        [$constructorParameterType],
×
UNCOV
345
                        $attributeContext['deserialization_path'],
×
UNCOV
346
                        true
×
UNCOV
347
                    );
×
UNCOV
348
                    $context['not_normalizable_value_exceptions'][] = $exception;
×
349
                }
350
            }
351

UNCOV
352
            if ($missingConstructorArguments) {
×
UNCOV
353
                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);
×
354
            }
355

UNCOV
356
            if (\count($context['not_normalizable_value_exceptions'] ?? []) > 0) {
×
357
                return $reflectionClass->newInstanceWithoutConstructor();
×
358
            }
359

UNCOV
360
            if ($constructor->isConstructor()) {
×
UNCOV
361
                return $reflectionClass->newInstanceArgs($params);
×
362
            }
363

364
            return $constructor->invokeArgs(null, $params);
×
365
        }
366

UNCOV
367
        return new $class();
×
368
    }
369

370
    protected function getClassDiscriminatorResolvedClass(array $data, string $class, array $context = []): string
371
    {
UNCOV
372
        if (null === $this->classDiscriminatorResolver || (null === $mapping = $this->classDiscriminatorResolver->getMappingForClass($class))) {
×
UNCOV
373
            return $class;
×
374
        }
375

UNCOV
376
        if (!isset($data[$mapping->getTypeProperty()])) {
×
377
            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());
×
378
        }
379

UNCOV
380
        $type = $data[$mapping->getTypeProperty()];
×
UNCOV
381
        if (null === ($mappedClass = $mapping->getClassForType($type))) {
×
382
            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);
×
383
        }
384

UNCOV
385
        return $mappedClass;
×
386
    }
387

388
    protected function createConstructorArgument($parameterData, string $key, \ReflectionParameter $constructorParameter, array $context, ?string $format = null): mixed
389
    {
UNCOV
390
        return $this->createAndValidateAttributeValue($constructorParameter->name, $parameterData, $format, $context);
×
391
    }
392

393
    /**
394
     * {@inheritdoc}
395
     *
396
     * Unused in this context.
397
     *
398
     * @return string[]
399
     */
400
    protected function extractAttributes($object, $format = null, array $context = []): array
401
    {
402
        return [];
×
403
    }
404

405
    /**
406
     * {@inheritdoc}
407
     */
408
    protected function getAllowedAttributes(string|object $classOrObject, array $context, bool $attributesAsString = false): array|bool
409
    {
UNCOV
410
        if (!$this->resourceClassResolver->isResourceClass($context['resource_class'])) {
×
UNCOV
411
            return parent::getAllowedAttributes($classOrObject, $context, $attributesAsString);
×
412
        }
413

UNCOV
414
        $resourceClass = $this->resourceClassResolver->getResourceClass(null, $context['resource_class']); // fix for abstract classes and interfaces
×
UNCOV
415
        $options = $this->getFactoryOptions($context);
×
UNCOV
416
        $propertyNames = $this->propertyNameCollectionFactory->create($resourceClass, $options);
×
417

UNCOV
418
        $allowedAttributes = [];
×
UNCOV
419
        foreach ($propertyNames as $propertyName) {
×
UNCOV
420
            $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $propertyName, $options);
×
421

422
            if (
UNCOV
423
                $this->isAllowedAttribute($classOrObject, $propertyName, null, $context)
×
UNCOV
424
                && (isset($context['api_normalize']) && $propertyMetadata->isReadable()
×
UNCOV
425
                    || isset($context['api_denormalize']) && ($propertyMetadata->isWritable() || !\is_object($classOrObject) && $propertyMetadata->isInitializable())
×
426
                )
427
            ) {
UNCOV
428
                $allowedAttributes[] = $propertyName;
×
429
            }
430
        }
431

UNCOV
432
        return $allowedAttributes;
×
433
    }
434

435
    /**
436
     * {@inheritdoc}
437
     */
438
    protected function isAllowedAttribute(object|string $classOrObject, string $attribute, ?string $format = null, array $context = []): bool
439
    {
UNCOV
440
        if (!parent::isAllowedAttribute($classOrObject, $attribute, $format, $context)) {
×
UNCOV
441
            return false;
×
442
        }
443

UNCOV
444
        return $this->canAccessAttribute(\is_object($classOrObject) ? $classOrObject : null, $attribute, $context);
×
445
    }
446

447
    /**
448
     * Check if access to the attribute is granted.
449
     */
450
    protected function canAccessAttribute(?object $object, string $attribute, array $context = []): bool
451
    {
UNCOV
452
        if (!$this->resourceClassResolver->isResourceClass($context['resource_class'])) {
×
UNCOV
453
            return true;
×
454
        }
455

UNCOV
456
        $options = $this->getFactoryOptions($context);
×
UNCOV
457
        $propertyMetadata = $this->propertyMetadataFactory->create($context['resource_class'], $attribute, $options);
×
UNCOV
458
        $security = $propertyMetadata->getSecurity() ?? $propertyMetadata->getPolicy();
×
UNCOV
459
        if (null !== $this->resourceAccessChecker && $security) {
×
UNCOV
460
            return $this->resourceAccessChecker->isGranted($context['resource_class'], $security, [
×
UNCOV
461
                'object' => $object,
×
UNCOV
462
                'property' => $attribute,
×
UNCOV
463
            ]);
×
464
        }
465

UNCOV
466
        return true;
×
467
    }
468

469
    /**
470
     * Check if access to the attribute is granted.
471
     */
472
    protected function canAccessAttributePostDenormalize(?object $object, ?object $previousObject, string $attribute, array $context = []): bool
473
    {
UNCOV
474
        $options = $this->getFactoryOptions($context);
×
UNCOV
475
        $propertyMetadata = $this->propertyMetadataFactory->create($context['resource_class'], $attribute, $options);
×
UNCOV
476
        $security = $propertyMetadata->getSecurityPostDenormalize();
×
UNCOV
477
        if ($this->resourceAccessChecker && $security) {
×
UNCOV
478
            return $this->resourceAccessChecker->isGranted($context['resource_class'], $security, [
×
UNCOV
479
                'object' => $object,
×
UNCOV
480
                'previous_object' => $previousObject,
×
UNCOV
481
                'property' => $attribute,
×
UNCOV
482
            ]);
×
483
        }
484

UNCOV
485
        return true;
×
486
    }
487

488
    /**
489
     * {@inheritdoc}
490
     */
491
    protected function setAttributeValue(object $object, string $attribute, mixed $value, ?string $format = null, array $context = []): void
492
    {
493
        try {
UNCOV
494
            $this->setValue($object, $attribute, $this->createAttributeValue($attribute, $value, $format, $context));
×
UNCOV
495
        } catch (NotNormalizableValueException $exception) {
×
496
            // Only throw if collecting denormalization errors is disabled.
UNCOV
497
            if (!isset($context['not_normalizable_value_exceptions'])) {
×
UNCOV
498
                throw $exception;
×
499
            }
500
        }
501
    }
502

503
    /**
504
     * Validates the type of the value. Allows using integers as floats for JSON formats.
505
     *
506
     * @throws NotNormalizableValueException
507
     */
508
    protected function validateType(string $attribute, Type $type, mixed $value, ?string $format = null, array $context = []): void
509
    {
UNCOV
510
        $builtinType = $type->getBuiltinType();
×
UNCOV
511
        if (Type::BUILTIN_TYPE_FLOAT === $builtinType && null !== $format && str_contains($format, 'json')) {
×
UNCOV
512
            $isValid = \is_float($value) || \is_int($value);
×
513
        } else {
UNCOV
514
            $isValid = \call_user_func('is_'.$builtinType, $value);
×
515
        }
516

UNCOV
517
        if (!$isValid) {
×
UNCOV
518
            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);
×
519
        }
520
    }
521

522
    /**
523
     * Denormalizes a collection of objects.
524
     *
525
     * @throws NotNormalizableValueException
526
     */
527
    protected function denormalizeCollection(string $attribute, ApiProperty $propertyMetadata, Type $type, string $className, mixed $value, ?string $format, array $context): array
528
    {
UNCOV
529
        if (!\is_array($value)) {
×
UNCOV
530
            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);
×
531
        }
532

UNCOV
533
        $values = [];
×
UNCOV
534
        $childContext = $this->createChildContext($this->createOperationContext($context, $className), $attribute, $format);
×
UNCOV
535
        $collectionKeyTypes = $type->getCollectionKeyTypes();
×
UNCOV
536
        foreach ($value as $index => $obj) {
×
UNCOV
537
            $currentChildContext = $childContext;
×
UNCOV
538
            if (isset($childContext['deserialization_path'])) {
×
UNCOV
539
                $currentChildContext['deserialization_path'] = "{$childContext['deserialization_path']}[{$index}]";
×
540
            }
541

542
            // no typehint provided on collection key
UNCOV
543
            if (!$collectionKeyTypes) {
×
544
                $values[$index] = $this->denormalizeRelation($attribute, $propertyMetadata, $className, $obj, $format, $currentChildContext);
×
545
                continue;
×
546
            }
547

548
            // validate collection key typehint
UNCOV
549
            foreach ($collectionKeyTypes as $collectionKeyType) {
×
UNCOV
550
                $collectionKeyBuiltinType = $collectionKeyType->getBuiltinType();
×
UNCOV
551
                if (!\call_user_func('is_'.$collectionKeyBuiltinType, $index)) {
×
UNCOV
552
                    continue;
×
553
                }
554

UNCOV
555
                $values[$index] = $this->denormalizeRelation($attribute, $propertyMetadata, $className, $obj, $format, $currentChildContext);
×
UNCOV
556
                continue 2;
×
557
            }
UNCOV
558
            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);
×
559
        }
560

UNCOV
561
        return $values;
×
562
    }
563

564
    /**
565
     * Denormalizes a relation.
566
     *
567
     * @throws LogicException
568
     * @throws UnexpectedValueException
569
     * @throws NotNormalizableValueException
570
     */
571
    protected function denormalizeRelation(string $attributeName, ApiProperty $propertyMetadata, string $className, mixed $value, ?string $format, array $context): ?object
572
    {
UNCOV
573
        if (\is_string($value)) {
×
574
            try {
UNCOV
575
                return $this->iriConverter->getResourceFromIri($value, $context + ['fetch_data' => true]);
×
UNCOV
576
            } catch (ItemNotFoundException $e) {
×
UNCOV
577
                if (!isset($context['not_normalizable_value_exceptions'])) {
×
UNCOV
578
                    throw new UnexpectedValueException($e->getMessage(), $e->getCode(), $e);
×
579
                }
580
                $context['not_normalizable_value_exceptions'][] = NotNormalizableValueException::createForUnexpectedDataType(
×
581
                    $e->getMessage(),
×
582
                    $value,
×
583
                    [$className],
×
584
                    $context['deserialization_path'] ?? null,
×
585
                    true,
×
586
                    $e->getCode(),
×
587
                    $e
×
588
                );
×
589

590
                return null;
×
UNCOV
591
            } catch (InvalidArgumentException $e) {
×
UNCOV
592
                if (!isset($context['not_normalizable_value_exceptions'])) {
×
UNCOV
593
                    throw new UnexpectedValueException(\sprintf('Invalid IRI "%s".', $value), $e->getCode(), $e);
×
594
                }
595
                $context['not_normalizable_value_exceptions'][] = NotNormalizableValueException::createForUnexpectedDataType(
×
596
                    $e->getMessage(),
×
597
                    $value,
×
598
                    [$className],
×
599
                    $context['deserialization_path'] ?? null,
×
600
                    true,
×
601
                    $e->getCode(),
×
602
                    $e
×
603
                );
×
604

605
                return null;
×
606
            }
607
        }
608

UNCOV
609
        if ($propertyMetadata->isWritableLink()) {
×
UNCOV
610
            $context['api_allow_update'] = true;
×
611

UNCOV
612
            if (!$this->serializer instanceof DenormalizerInterface) {
×
613
                throw new LogicException(\sprintf('The injected serializer must be an instance of "%s".', DenormalizerInterface::class));
×
614
            }
615

UNCOV
616
            $item = $this->serializer->denormalize($value, $className, $format, $context);
×
UNCOV
617
            if (!\is_object($item) && null !== $item) {
×
618
                throw new \UnexpectedValueException('Expected item to be an object or null.');
×
619
            }
620

UNCOV
621
            return $item;
×
622
        }
623

624
        if (!\is_array($value)) {
×
625
            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, true);
×
626
        }
627

628
        throw NotNormalizableValueException::createForUnexpectedDataType(\sprintf('Nested documents for attribute "%s" are not allowed. Use IRIs instead.', $attributeName), $value, [Type::BUILTIN_TYPE_ARRAY, Type::BUILTIN_TYPE_STRING], $context['deserialization_path'] ?? null, true);
×
629
    }
630

631
    /**
632
     * Gets the options for the property name collection / property metadata factories.
633
     */
634
    protected function getFactoryOptions(array $context): array
635
    {
UNCOV
636
        $options = [];
×
UNCOV
637
        if (isset($context[self::GROUPS])) {
×
638
            /* @see https://github.com/symfony/symfony/blob/v4.2.6/src/Symfony/Component/PropertyInfo/Extractor/SerializerExtractor.php */
UNCOV
639
            $options['serializer_groups'] = (array) $context[self::GROUPS];
×
640
        }
641

UNCOV
642
        $operationCacheKey = ($context['resource_class'] ?? '').($context['operation_name'] ?? '').($context['root_operation_name'] ?? '');
×
UNCOV
643
        $suffix = ($context['api_normalize'] ?? '') ? 'n' : '';
×
UNCOV
644
        if ($operationCacheKey && isset($this->localFactoryOptionsCache[$operationCacheKey.$suffix])) {
×
UNCOV
645
            return $options + $this->localFactoryOptionsCache[$operationCacheKey.$suffix];
×
646
        }
647

648
        // This is a hot spot
UNCOV
649
        if (isset($context['resource_class'])) {
×
650
            // Note that the groups need to be read on the root operation
UNCOV
651
            if ($operation = ($context['root_operation'] ?? null)) {
×
UNCOV
652
                $options['normalization_groups'] = $operation->getNormalizationContext()['groups'] ?? null;
×
UNCOV
653
                $options['denormalization_groups'] = $operation->getDenormalizationContext()['groups'] ?? null;
×
UNCOV
654
                $options['operation_name'] = $operation->getName();
×
655
            }
656
        }
657

UNCOV
658
        return $options + $this->localFactoryOptionsCache[$operationCacheKey.$suffix] = $options;
×
659
    }
660

661
    /**
662
     * {@inheritdoc}
663
     *
664
     * @throws UnexpectedValueException
665
     */
666
    protected function getAttributeValue(object $object, string $attribute, ?string $format = null, array $context = []): mixed
667
    {
UNCOV
668
        $context['api_attribute'] = $attribute;
×
UNCOV
669
        $context['property_metadata'] = $propertyMetadata = $this->propertyMetadataFactory->create($context['resource_class'], $attribute, $this->getFactoryOptions($context));
×
670

UNCOV
671
        if ($context['api_denormalize'] ?? false) {
×
UNCOV
672
            return $this->propertyAccessor->getValue($object, $attribute);
×
673
        }
674

UNCOV
675
        $types = $propertyMetadata->getBuiltinTypes() ?? [];
×
676

UNCOV
677
        foreach ($types as $type) {
×
678
            if (
UNCOV
679
                $type->isCollection()
×
UNCOV
680
                && ($collectionValueType = $type->getCollectionValueTypes()[0] ?? null)
×
UNCOV
681
                && ($className = $collectionValueType->getClassName())
×
UNCOV
682
                && $this->resourceClassResolver->isResourceClass($className)
×
683
            ) {
UNCOV
684
                $childContext = $this->createChildContext($this->createOperationContext($context, $className), $attribute, $format);
×
685

686
                // @see ApiPlatform\Hal\Serializer\ItemNormalizer:getComponents logic for intentional duplicate content
687
                // @see ApiPlatform\JsonApi\Serializer\ItemNormalizer:getComponents logic for intentional duplicate content
UNCOV
688
                if ('jsonld' === $format && $itemUriTemplate = $propertyMetadata->getUriTemplate()) {
×
UNCOV
689
                    $operation = $this->resourceMetadataCollectionFactory->create($className)->getOperation(
×
UNCOV
690
                        operationName: $itemUriTemplate,
×
UNCOV
691
                        forceCollection: true,
×
UNCOV
692
                        httpOperation: true
×
UNCOV
693
                    );
×
694

UNCOV
695
                    return $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_PATH, $operation, $childContext);
×
696
                }
697

UNCOV
698
                $attributeValue = $this->propertyAccessor->getValue($object, $attribute);
×
699

UNCOV
700
                if (!is_iterable($attributeValue)) {
×
701
                    throw new UnexpectedValueException('Unexpected non-iterable value for to-many relation.');
×
702
                }
703

UNCOV
704
                $resourceClass = $this->resourceClassResolver->getResourceClass($attributeValue, $className);
×
705

UNCOV
706
                $data = $this->normalizeCollectionOfRelations($propertyMetadata, $attributeValue, $resourceClass, $format, $childContext);
×
UNCOV
707
                $context['data'] = $data;
×
UNCOV
708
                $context['type'] = $type;
×
709

UNCOV
710
                if ($this->tagCollector) {
×
UNCOV
711
                    $this->tagCollector->collect($context);
×
712
                }
713

UNCOV
714
                return $data;
×
715
            }
716

717
            if (
UNCOV
718
                ($className = $type->getClassName())
×
UNCOV
719
                && $this->resourceClassResolver->isResourceClass($className)
×
720
            ) {
UNCOV
721
                $childContext = $this->createChildContext($this->createOperationContext($context, $className), $attribute, $format);
×
UNCOV
722
                unset($childContext['iri'], $childContext['uri_variables'], $childContext['item_uri_template']);
×
UNCOV
723
                if ('jsonld' === $format && $uriTemplate = $propertyMetadata->getUriTemplate()) {
×
UNCOV
724
                    $operation = $this->resourceMetadataCollectionFactory->create($className)->getOperation(
×
UNCOV
725
                        operationName: $uriTemplate,
×
UNCOV
726
                        httpOperation: true
×
UNCOV
727
                    );
×
728

UNCOV
729
                    return $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_PATH, $operation, $childContext);
×
730
                }
731

UNCOV
732
                $attributeValue = $this->propertyAccessor->getValue($object, $attribute);
×
733

UNCOV
734
                if (!\is_object($attributeValue) && null !== $attributeValue) {
×
735
                    throw new UnexpectedValueException('Unexpected non-object value for to-one relation.');
×
736
                }
737

UNCOV
738
                $resourceClass = $this->resourceClassResolver->getResourceClass($attributeValue, $className);
×
739

UNCOV
740
                $data = $this->normalizeRelation($propertyMetadata, $attributeValue, $resourceClass, $format, $childContext);
×
UNCOV
741
                $context['data'] = $data;
×
UNCOV
742
                $context['type'] = $type;
×
743

UNCOV
744
                if ($this->tagCollector) {
×
UNCOV
745
                    $this->tagCollector->collect($context);
×
746
                }
747

UNCOV
748
                return $data;
×
749
            }
750

UNCOV
751
            if (!$this->serializer instanceof NormalizerInterface) {
×
752
                throw new LogicException(\sprintf('The injected serializer must be an instance of "%s".', NormalizerInterface::class));
×
753
            }
754

UNCOV
755
            unset(
×
UNCOV
756
                $context['resource_class'],
×
UNCOV
757
                $context['force_resource_class'],
×
UNCOV
758
                $context['uri_variables'],
×
UNCOV
759
            );
×
760

761
            // Anonymous resources
UNCOV
762
            if ($className) {
×
UNCOV
763
                $childContext = $this->createChildContext($this->createOperationContext($context, $className), $attribute, $format);
×
UNCOV
764
                $childContext['output']['gen_id'] = $propertyMetadata->getGenId() ?? true;
×
765

UNCOV
766
                $attributeValue = $this->propertyAccessor->getValue($object, $attribute);
×
767

UNCOV
768
                return $this->serializer->normalize($attributeValue, $format, $childContext);
×
769
            }
770

UNCOV
771
            if ('array' === $type->getBuiltinType()) {
×
UNCOV
772
                if ($className = ($type->getCollectionValueTypes()[0] ?? null)?->getClassName()) {
×
UNCOV
773
                    $context = $this->createOperationContext($context, $className);
×
774
                }
775

UNCOV
776
                $childContext = $this->createChildContext($context, $attribute, $format);
×
UNCOV
777
                $childContext['output']['gen_id'] = $propertyMetadata->getGenId() ?? true;
×
778

UNCOV
779
                $attributeValue = $this->propertyAccessor->getValue($object, $attribute);
×
780

UNCOV
781
                return $this->serializer->normalize($attributeValue, $format, $childContext);
×
782
            }
783
        }
784

UNCOV
785
        if (!$this->serializer instanceof NormalizerInterface) {
×
786
            throw new LogicException(\sprintf('The injected serializer must be an instance of "%s".', NormalizerInterface::class));
×
787
        }
788

UNCOV
789
        unset(
×
UNCOV
790
            $context['resource_class'],
×
UNCOV
791
            $context['force_resource_class'],
×
UNCOV
792
            $context['uri_variables']
×
UNCOV
793
        );
×
794

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

UNCOV
797
        return $this->serializer->normalize($attributeValue, $format, $context);
×
798
    }
799

800
    /**
801
     * Normalizes a collection of relations (to-many).
802
     *
803
     * @throws UnexpectedValueException
804
     */
805
    protected function normalizeCollectionOfRelations(ApiProperty $propertyMetadata, iterable $attributeValue, string $resourceClass, ?string $format, array $context): array
806
    {
UNCOV
807
        $value = [];
×
UNCOV
808
        foreach ($attributeValue as $index => $obj) {
×
UNCOV
809
            if (!\is_object($obj) && null !== $obj) {
×
810
                throw new UnexpectedValueException('Unexpected non-object element in to-many relation.');
×
811
            }
812

813
            // update context, if concrete object class deviates from general relation class (e.g. in case of polymorphic resources)
UNCOV
814
            $objResourceClass = $this->resourceClassResolver->getResourceClass($obj, $resourceClass);
×
UNCOV
815
            $context['resource_class'] = $objResourceClass;
×
UNCOV
816
            if ($this->resourceMetadataCollectionFactory) {
×
UNCOV
817
                $context['operation'] = $this->resourceMetadataCollectionFactory->create($objResourceClass)->getOperation();
×
818
            }
819

UNCOV
820
            $value[$index] = $this->normalizeRelation($propertyMetadata, $obj, $resourceClass, $format, $context);
×
821
        }
822

UNCOV
823
        return $value;
×
824
    }
825

826
    /**
827
     * Normalizes a relation.
828
     *
829
     * @throws LogicException
830
     * @throws UnexpectedValueException
831
     */
832
    protected function normalizeRelation(ApiProperty $propertyMetadata, ?object $relatedObject, string $resourceClass, ?string $format, array $context): \ArrayObject|array|string|null
833
    {
UNCOV
834
        if (null === $relatedObject || !empty($context['attributes']) || $propertyMetadata->isReadableLink()) {
×
UNCOV
835
            if (!$this->serializer instanceof NormalizerInterface) {
×
836
                throw new LogicException(\sprintf('The injected serializer must be an instance of "%s".', NormalizerInterface::class));
×
837
            }
838

UNCOV
839
            $relatedContext = $this->createOperationContext($context, $resourceClass);
×
UNCOV
840
            $normalizedRelatedObject = $this->serializer->normalize($relatedObject, $format, $relatedContext);
×
UNCOV
841
            if (!\is_string($normalizedRelatedObject) && !\is_array($normalizedRelatedObject) && !$normalizedRelatedObject instanceof \ArrayObject && null !== $normalizedRelatedObject) {
×
842
                throw new UnexpectedValueException('Expected normalized relation to be an IRI, array, \ArrayObject or null');
×
843
            }
844

UNCOV
845
            return $normalizedRelatedObject;
×
846
        }
847

UNCOV
848
        $context['iri'] = $iri = $this->iriConverter->getIriFromResource(resource: $relatedObject, context: $context);
×
UNCOV
849
        $context['data'] = $iri;
×
UNCOV
850
        $context['object'] = $relatedObject;
×
UNCOV
851
        unset($context['property_metadata'], $context['api_attribute']);
×
852

UNCOV
853
        if ($this->tagCollector) {
×
UNCOV
854
            $this->tagCollector->collect($context);
×
UNCOV
855
        } elseif (isset($context['resources'])) {
×
856
            $context['resources'][$iri] = $iri;
×
857
        }
858

UNCOV
859
        $push = $propertyMetadata->getPush() ?? false;
×
UNCOV
860
        if (isset($context['resources_to_push']) && $push) {
×
861
            $context['resources_to_push'][$iri] = $iri;
×
862
        }
863

UNCOV
864
        return $iri;
×
865
    }
866

867
    private function createAttributeValue(string $attribute, mixed $value, ?string $format = null, array &$context = []): mixed
868
    {
869
        try {
UNCOV
870
            return $this->createAndValidateAttributeValue($attribute, $value, $format, $context);
×
UNCOV
871
        } catch (NotNormalizableValueException $exception) {
×
UNCOV
872
            if (!isset($context['not_normalizable_value_exceptions'])) {
×
UNCOV
873
                throw $exception;
×
874
            }
875
            $context['not_normalizable_value_exceptions'][] = $exception;
×
876

877
            throw $exception;
×
878
        }
879
    }
880

881
    private function createAndValidateAttributeValue(string $attribute, mixed $value, ?string $format = null, array $context = []): mixed
882
    {
UNCOV
883
        $propertyMetadata = $this->propertyMetadataFactory->create($context['resource_class'], $attribute, $this->getFactoryOptions($context));
×
UNCOV
884
        $types = $propertyMetadata->getBuiltinTypes() ?? [];
×
UNCOV
885
        $isMultipleTypes = \count($types) > 1;
×
886

UNCOV
887
        foreach ($types as $type) {
×
UNCOV
888
            if (null === $value && ($type->isNullable() || ($context[static::DISABLE_TYPE_ENFORCEMENT] ?? false))) {
×
UNCOV
889
                return $value;
×
890
            }
891

UNCOV
892
            $collectionValueType = $type->getCollectionValueTypes()[0] ?? null;
×
893

894
            /* From @see AbstractObjectNormalizer::validateAndDenormalize() */
895
            // Fix a collection that contains the only one element
896
            // This is special to xml format only
UNCOV
897
            if ('xml' === $format && null !== $collectionValueType && (!\is_array($value) || !\is_int(key($value)))) {
×
UNCOV
898
                $value = [$value];
×
899
            }
900

901
            if (
UNCOV
902
                $type->isCollection()
×
UNCOV
903
                && null !== $collectionValueType
×
UNCOV
904
                && null !== ($className = $collectionValueType->getClassName())
×
UNCOV
905
                && $this->resourceClassResolver->isResourceClass($className)
×
906
            ) {
UNCOV
907
                $resourceClass = $this->resourceClassResolver->getResourceClass(null, $className);
×
UNCOV
908
                $context['resource_class'] = $resourceClass;
×
UNCOV
909
                unset($context['uri_variables']);
×
910

UNCOV
911
                return $this->denormalizeCollection($attribute, $propertyMetadata, $type, $resourceClass, $value, $format, $context);
×
912
            }
913

914
            if (
UNCOV
915
                null !== ($className = $type->getClassName())
×
UNCOV
916
                && $this->resourceClassResolver->isResourceClass($className)
×
917
            ) {
UNCOV
918
                $resourceClass = $this->resourceClassResolver->getResourceClass(null, $className);
×
UNCOV
919
                $childContext = $this->createChildContext($this->createOperationContext($context, $resourceClass), $attribute, $format);
×
920

UNCOV
921
                return $this->denormalizeRelation($attribute, $propertyMetadata, $resourceClass, $value, $format, $childContext);
×
922
            }
923

924
            if (
UNCOV
925
                $type->isCollection()
×
UNCOV
926
                && null !== $collectionValueType
×
UNCOV
927
                && null !== ($className = $collectionValueType->getClassName())
×
UNCOV
928
                && \is_array($value)
×
929
            ) {
UNCOV
930
                if (!$this->serializer instanceof DenormalizerInterface) {
×
931
                    throw new LogicException(\sprintf('The injected serializer must be an instance of "%s".', DenormalizerInterface::class));
×
932
                }
933

UNCOV
934
                unset($context['resource_class'], $context['uri_variables']);
×
935

UNCOV
936
                return $this->serializer->denormalize($value, $className.'[]', $format, $context);
×
937
            }
938

UNCOV
939
            if (null !== $className = $type->getClassName()) {
×
UNCOV
940
                if (!$this->serializer instanceof DenormalizerInterface) {
×
941
                    throw new LogicException(\sprintf('The injected serializer must be an instance of "%s".', DenormalizerInterface::class));
×
942
                }
943

UNCOV
944
                unset($context['resource_class'], $context['uri_variables']);
×
945

UNCOV
946
                return $this->serializer->denormalize($value, $className, $format, $context);
×
947
            }
948

949
            /* From @see AbstractObjectNormalizer::validateAndDenormalize() */
950
            // In XML and CSV all basic datatypes are represented as strings, it is e.g. not possible to determine,
951
            // if a value is meant to be a string, float, int or a boolean value from the serialized representation.
952
            // That's why we have to transform the values, if one of these non-string basic datatypes is expected.
UNCOV
953
            if (\is_string($value) && (XmlEncoder::FORMAT === $format || CsvEncoder::FORMAT === $format)) {
×
UNCOV
954
                if ('' === $value && $type->isNullable() && \in_array($type->getBuiltinType(), [Type::BUILTIN_TYPE_BOOL, Type::BUILTIN_TYPE_INT, Type::BUILTIN_TYPE_FLOAT], true)) {
×
955
                    return null;
×
956
                }
957

UNCOV
958
                switch ($type->getBuiltinType()) {
×
UNCOV
959
                    case Type::BUILTIN_TYPE_BOOL:
×
960
                        // according to http://www.w3.org/TR/xmlschema-2/#boolean, valid representations are "false", "true", "0" and "1"
UNCOV
961
                        if ('false' === $value || '0' === $value) {
×
UNCOV
962
                            $value = false;
×
UNCOV
963
                        } elseif ('true' === $value || '1' === $value) {
×
UNCOV
964
                            $value = true;
×
965
                        } else {
966
                            // union/intersect types: try the next type, if not valid, an exception will be thrown at the end
967
                            if ($isMultipleTypes) {
×
968
                                break 2;
×
969
                            }
970
                            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);
×
971
                        }
UNCOV
972
                        break;
×
UNCOV
973
                    case Type::BUILTIN_TYPE_INT:
×
UNCOV
974
                        if (ctype_digit($value) || ('-' === $value[0] && ctype_digit(substr($value, 1)))) {
×
UNCOV
975
                            $value = (int) $value;
×
976
                        } else {
977
                            // union/intersect types: try the next type, if not valid, an exception will be thrown at the end
978
                            if ($isMultipleTypes) {
×
979
                                break 2;
×
980
                            }
981
                            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);
×
982
                        }
UNCOV
983
                        break;
×
UNCOV
984
                    case Type::BUILTIN_TYPE_FLOAT:
×
UNCOV
985
                        if (is_numeric($value)) {
×
UNCOV
986
                            return (float) $value;
×
987
                        }
988

989
                        switch ($value) {
UNCOV
990
                            case 'NaN':
×
UNCOV
991
                                return \NAN;
×
UNCOV
992
                            case 'INF':
×
UNCOV
993
                                return \INF;
×
UNCOV
994
                            case '-INF':
×
UNCOV
995
                                return -\INF;
×
996
                            default:
997
                                // union/intersect types: try the next type, if not valid, an exception will be thrown at the end
998
                                if ($isMultipleTypes) {
×
999
                                    break 3;
×
1000
                                }
1001
                                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);
×
1002
                        }
1003
                }
1004
            }
1005

UNCOV
1006
            if ($context[static::DISABLE_TYPE_ENFORCEMENT] ?? false) {
×
1007
                return $value;
×
1008
            }
1009

1010
            try {
UNCOV
1011
                $this->validateType($attribute, $type, $value, $format, $context);
×
1012

UNCOV
1013
                break;
×
UNCOV
1014
            } catch (NotNormalizableValueException $e) {
×
1015
                // union/intersect types: try the next type
UNCOV
1016
                if (!$isMultipleTypes) {
×
UNCOV
1017
                    throw $e;
×
1018
                }
1019
            }
1020
        }
1021

UNCOV
1022
        return $value;
×
1023
    }
1024

1025
    /**
1026
     * Sets a value of the object using the PropertyAccess component.
1027
     */
1028
    private function setValue(object $object, string $attributeName, mixed $value): void
1029
    {
1030
        try {
UNCOV
1031
            $this->propertyAccessor->setValue($object, $attributeName, $value);
×
UNCOV
1032
        } catch (NoSuchPropertyException) {
×
1033
            // Properties not found are ignored
1034
        }
1035
    }
1036
}
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