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

api-platform / core / 10489772975

21 Aug 2024 12:22PM UTC coverage: 7.704%. Remained the same
10489772975

push

github

web-flow
doc: link monorepo to test laravel (#6530)

12476 of 161932 relevant lines covered (7.7%)

23.0 hits per line

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

84.73
/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
    {
67
        if (!isset($defaultContext['circular_reference_handler'])) {
2,255✔
68
            $defaultContext['circular_reference_handler'] = fn ($object): ?string => $this->iriConverter->getIriFromResource($object);
2,255✔
69
        }
70

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

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

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

91
        return $this->resourceClassResolver->isResourceClass($class);
1,890✔
92
    }
93

94
    public function getSupportedTypes(?string $format): array
95
    {
96
        return [
2,071✔
97
            'object' => true,
2,071✔
98
        ];
2,071✔
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
    {
108
        $resourceClass = $context['force_resource_class'] ?? $this->getObjectClass($object);
1,920✔
109
        if ($outputClass = $this->getOutputClass($context)) {
1,920✔
110
            if (!$this->serializer instanceof NormalizerInterface) {
46✔
111
                throw new LogicException('Cannot normalize the output because the injected serializer is not a normalizer');
×
112
            }
113

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

119
            return $this->serializer->normalize($object, $format, $context);
46✔
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
124
        if (isset($context['operation']) && $context['operation'] instanceof CollectionOperationInterface) {
1,920✔
125
            unset($context['operation_name'], $context['operation'], $context['iri']);
18✔
126
        }
127

128
        if ($this->resourceClassResolver->isResourceClass($resourceClass)) {
1,920✔
129
            $context = $this->initContext($resourceClass, $context);
1,878✔
130
        }
131

132
        $context['api_normalize'] = true;
1,920✔
133
        $iri = $context['iri'] ??= $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_URL, $context['operation'] ?? null, $context);
1,920✔
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
         */
145
        $emptyResourceAsIri = $context['api_empty_resource_as_iri'] ?? false;
1,920✔
146
        unset($context['api_empty_resource_as_iri']);
1,920✔
147

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

152
        $context['object'] = $object;
1,920✔
153
        $context['format'] = $format;
1,920✔
154

155
        $data = parent::normalize($object, $format, $context);
1,920✔
156

157
        $context['data'] = $data;
1,920✔
158
        unset($context['property_metadata'], $context['api_attribute']);
1,920✔
159

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

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

167
            return $iri;
×
168
        }
169

170
        if ($this->tagCollector) {
1,920✔
171
            $this->tagCollector->collect($context);
1,641✔
172
        }
173

174
        return $data;
1,920✔
175
    }
176

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

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

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

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

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

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

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

216
        $context['api_denormalize'] = true;
642✔
217

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

223
        if (\is_string($data)) {
642✔
224
            try {
225
                return $this->iriConverter->getResourceFromIri($data, $context + ['fetch_data' => true]);
4✔
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

233
        if (!\is_array($data)) {
639✔
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);
3✔
235
        }
236

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

240
        if (!$this->resourceClassResolver->isResourceClass($class)) {
598✔
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.
246
        if (null !== $objectToPopulate && null === $previousObject) {
598✔
247
            return $object;
×
248
        }
249

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

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

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

270
        return $object;
598✔
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
    {
283
        if (null !== $object = $this->extractObjectToPopulate($class, $context, static::OBJECT_TO_POPULATE)) {
639✔
284
            unset($context[static::OBJECT_TO_POPULATE]);
137✔
285

286
            return $object;
137✔
287
        }
288

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

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

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

302
                $allowed = false === $allowedAttributes || (\is_array($allowedAttributes) && \in_array($paramName, $allowedAttributes, true));
32✔
303
                $ignored = !$this->isAllowedAttribute($class, $paramName, $format, $context);
32✔
304
                if ($constructorParameter->isVariadic()) {
32✔
305
                    if ($allowed && !$ignored && (isset($data[$key]) || \array_key_exists($key, $data))) {
×
306
                        if (!\is_array($data[$paramName])) {
×
307
                            throw new RuntimeException(\sprintf('Cannot create an instance of %s from serialized data because the variadic parameter %s can only accept an array.', $class, $constructorParameter->name));
×
308
                        }
309

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

324
                    // Don't run set for a parameter passed to the constructor
325
                    unset($data[$key]);
27✔
326
                } elseif (isset($context[static::DEFAULT_CONSTRUCTOR_ARGUMENTS][$class][$key])) {
23✔
327
                    $params[] = $context[static::DEFAULT_CONSTRUCTOR_ARGUMENTS][$class][$key];
×
328
                } elseif ($constructorParameter->isDefaultValueAvailable()) {
23✔
329
                    $params[] = $constructorParameter->getDefaultValue();
22✔
330
                } else {
331
                    if (!isset($context['not_normalizable_value_exceptions'])) {
4✔
332
                        $missingConstructorArguments[] = $constructorParameter->name;
3✔
333
                    }
334

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

340
            if ($missingConstructorArguments) {
230✔
341
                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);
3✔
342
            }
343

344
            if (\count($context['not_normalizable_value_exceptions'] ?? []) > 0) {
230✔
345
                return $reflectionClass->newInstanceWithoutConstructor();
1✔
346
            }
347

348
            if ($constructor->isConstructor()) {
229✔
349
                return $reflectionClass->newInstanceArgs($params);
229✔
350
            }
351

352
            return $constructor->invokeArgs(null, $params);
×
353
        }
354

355
        return new $class();
304✔
356
    }
357

358
    protected function getClassDiscriminatorResolvedClass(array $data, string $class, array $context = []): string
359
    {
360
        if (null === $this->classDiscriminatorResolver || (null === $mapping = $this->classDiscriminatorResolver->getMappingForClass($class))) {
524✔
361
            return $class;
524✔
362
        }
363

364
        if (!isset($data[$mapping->getTypeProperty()])) {
3✔
365
            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());
×
366
        }
367

368
        $type = $data[$mapping->getTypeProperty()];
3✔
369
        if (null === ($mappedClass = $mapping->getClassForType($type))) {
3✔
370
            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);
×
371
        }
372

373
        return $mappedClass;
3✔
374
    }
375

376
    protected function createConstructorArgument($parameterData, string $key, \ReflectionParameter $constructorParameter, array &$context, ?string $format = null): mixed
377
    {
378
        return $this->createAndValidateAttributeValue($constructorParameter->name, $parameterData, $format, $context);
28✔
379
    }
380

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

393
    /**
394
     * {@inheritdoc}
395
     */
396
    protected function getAllowedAttributes(string|object $classOrObject, array $context, bool $attributesAsString = false): array|bool
397
    {
398
        if (!$this->resourceClassResolver->isResourceClass($context['resource_class'])) {
1,939✔
399
            return parent::getAllowedAttributes($classOrObject, $context, $attributesAsString);
46✔
400
        }
401

402
        $resourceClass = $this->resourceClassResolver->getResourceClass(null, $context['resource_class']); // fix for abstract classes and interfaces
1,900✔
403
        $options = $this->getFactoryOptions($context);
1,900✔
404
        $propertyNames = $this->propertyNameCollectionFactory->create($resourceClass, $options);
1,900✔
405

406
        $allowedAttributes = [];
1,900✔
407
        foreach ($propertyNames as $propertyName) {
1,900✔
408
            $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $propertyName, $options);
1,891✔
409

410
            if (
411
                $this->isAllowedAttribute($classOrObject, $propertyName, null, $context)
1,891✔
412
                && (isset($context['api_normalize']) && $propertyMetadata->isReadable()
1,891✔
413
                    || isset($context['api_denormalize']) && ($propertyMetadata->isWritable() || !\is_object($classOrObject) && $propertyMetadata->isInitializable())
1,891✔
414
                )
415
            ) {
416
                $allowedAttributes[] = $propertyName;
1,879✔
417
            }
418
        }
419

420
        return $allowedAttributes;
1,900✔
421
    }
422

423
    /**
424
     * {@inheritdoc}
425
     */
426
    protected function isAllowedAttribute(object|string $classOrObject, string $attribute, ?string $format = null, array $context = []): bool
427
    {
428
        if (!parent::isAllowedAttribute($classOrObject, $attribute, $format, $context)) {
1,930✔
429
            return false;
306✔
430
        }
431

432
        return $this->canAccessAttribute(\is_object($classOrObject) ? $classOrObject : null, $attribute, $context);
1,927✔
433
    }
434

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

444
        $options = $this->getFactoryOptions($context);
1,888✔
445
        $propertyMetadata = $this->propertyMetadataFactory->create($context['resource_class'], $attribute, $options);
1,888✔
446
        $security = $propertyMetadata->getSecurity() ?? $propertyMetadata->getPolicy();
1,888✔
447
        if (null !== $this->resourceAccessChecker && $security) {
1,888✔
448
            return $this->resourceAccessChecker->isGranted($context['resource_class'], $security, [
93✔
449
                'object' => $object,
93✔
450
                'property' => $attribute,
93✔
451
            ]);
93✔
452
        }
453

454
        return true;
1,876✔
455
    }
456

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

473
        return true;
548✔
474
    }
475

476
    /**
477
     * {@inheritdoc}
478
     */
479
    protected function setAttributeValue(object $object, string $attribute, mixed $value, ?string $format = null, array $context = []): void
480
    {
481
        try {
482
            $this->setValue($object, $attribute, $this->createAttributeValue($attribute, $value, $format, $context));
555✔
483
        } catch (NotNormalizableValueException $exception) {
41✔
484
            // Only throw if collecting denormalization errors is disabled.
485
            if (!isset($context['not_normalizable_value_exceptions'])) {
29✔
486
                throw $exception;
28✔
487
            }
488
        }
489
    }
490

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

505
        if (!$isValid) {
485✔
506
            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);
21✔
507
        }
508
    }
509

510
    /**
511
     * Denormalizes a collection of objects.
512
     *
513
     * @throws NotNormalizableValueException
514
     */
515
    protected function denormalizeCollection(string $attribute, ApiProperty $propertyMetadata, Type $type, string $className, mixed $value, ?string $format, array $context): array
516
    {
517
        if (!\is_array($value)) {
44✔
518
            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);
4✔
519
        }
520

521
        $values = [];
40✔
522
        $childContext = $this->createChildContext($this->createOperationContext($context, $className), $attribute, $format);
40✔
523
        $collectionKeyTypes = $type->getCollectionKeyTypes();
40✔
524
        foreach ($value as $index => $obj) {
40✔
525
            // no typehint provided on collection key
526
            if (!$collectionKeyTypes) {
40✔
527
                $values[$index] = $this->denormalizeRelation($attribute, $propertyMetadata, $className, $obj, $format, $childContext);
×
528
                continue;
×
529
            }
530

531
            // validate collection key typehint
532
            foreach ($collectionKeyTypes as $collectionKeyType) {
40✔
533
                $collectionKeyBuiltinType = $collectionKeyType->getBuiltinType();
40✔
534
                if (!\call_user_func('is_'.$collectionKeyBuiltinType, $index)) {
40✔
535
                    continue;
3✔
536
                }
537

538
                $values[$index] = $this->denormalizeRelation($attribute, $propertyMetadata, $className, $obj, $format, $childContext);
37✔
539
                continue 2;
37✔
540
            }
541
            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);
3✔
542
        }
543

544
        return $values;
37✔
545
    }
546

547
    /**
548
     * Denormalizes a relation.
549
     *
550
     * @throws LogicException
551
     * @throws UnexpectedValueException
552
     * @throws NotNormalizableValueException
553
     */
554
    protected function denormalizeRelation(string $attributeName, ApiProperty $propertyMetadata, string $className, mixed $value, ?string $format, array $context): ?object
555
    {
556
        if (\is_string($value)) {
154✔
557
            try {
558
                return $this->iriConverter->getResourceFromIri($value, $context + ['fetch_data' => true]);
84✔
559
            } catch (ItemNotFoundException $e) {
9✔
560
                if (!isset($context['not_normalizable_value_exceptions'])) {
3✔
561
                    throw new UnexpectedValueException($e->getMessage(), $e->getCode(), $e);
3✔
562
                }
563
                $context['not_normalizable_value_exceptions'][] = NotNormalizableValueException::createForUnexpectedDataType(
×
564
                    $e->getMessage(),
×
565
                    $value,
×
566
                    [$className],
×
567
                    $context['deserialization_path'] ?? null,
×
568
                    true,
×
569
                    $e->getCode(),
×
570
                    $e
×
571
                );
×
572

573
                return null;
×
574
            } catch (InvalidArgumentException $e) {
6✔
575
                if (!isset($context['not_normalizable_value_exceptions'])) {
6✔
576
                    throw new UnexpectedValueException(\sprintf('Invalid IRI "%s".', $value), $e->getCode(), $e);
6✔
577
                }
578
                $context['not_normalizable_value_exceptions'][] = NotNormalizableValueException::createForUnexpectedDataType(
×
579
                    $e->getMessage(),
×
580
                    $value,
×
581
                    [$className],
×
582
                    $context['deserialization_path'] ?? null,
×
583
                    true,
×
584
                    $e->getCode(),
×
585
                    $e
×
586
                );
×
587

588
                return null;
×
589
            }
590
        }
591

592
        if ($propertyMetadata->isWritableLink()) {
73✔
593
            $context['api_allow_update'] = true;
71✔
594

595
            if (!$this->serializer instanceof DenormalizerInterface) {
71✔
596
                throw new LogicException(\sprintf('The injected serializer must be an instance of "%s".', DenormalizerInterface::class));
×
597
            }
598

599
            $item = $this->serializer->denormalize($value, $className, $format, $context);
71✔
600
            if (!\is_object($item) && null !== $item) {
65✔
601
                throw new \UnexpectedValueException('Expected item to be an object or null.');
×
602
            }
603

604
            return $item;
65✔
605
        }
606

607
        if (!\is_array($value)) {
2✔
608
            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);
1✔
609
        }
610

611
        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);
1✔
612
    }
613

614
    /**
615
     * Gets the options for the property name collection / property metadata factories.
616
     */
617
    protected function getFactoryOptions(array $context): array
618
    {
619
        $options = [];
1,939✔
620
        if (isset($context[self::GROUPS])) {
1,939✔
621
            /* @see https://github.com/symfony/symfony/blob/v4.2.6/src/Symfony/Component/PropertyInfo/Extractor/SerializerExtractor.php */
622
            $options['serializer_groups'] = (array) $context[self::GROUPS];
668✔
623
        }
624

625
        $operationCacheKey = ($context['resource_class'] ?? '').($context['operation_name'] ?? '').($context['root_operation_name'] ?? '');
1,939✔
626
        $suffix = ($context['api_normalize'] ?? '') ? 'n' : '';
1,939✔
627
        if ($operationCacheKey && isset($this->localFactoryOptionsCache[$operationCacheKey.$suffix])) {
1,939✔
628
            return $options + $this->localFactoryOptionsCache[$operationCacheKey.$suffix];
1,933✔
629
        }
630

631
        // This is a hot spot
632
        if (isset($context['resource_class'])) {
1,939✔
633
            // Note that the groups need to be read on the root operation
634
            if ($operation = ($context['root_operation'] ?? null)) {
1,939✔
635
                $options['normalization_groups'] = $operation->getNormalizationContext()['groups'] ?? null;
743✔
636
                $options['denormalization_groups'] = $operation->getDenormalizationContext()['groups'] ?? null;
743✔
637
                $options['operation_name'] = $operation->getName();
743✔
638
            }
639
        }
640

641
        return $options + $this->localFactoryOptionsCache[$operationCacheKey.$suffix] = $options;
1,939✔
642
    }
643

644
    /**
645
     * {@inheritdoc}
646
     *
647
     * @throws UnexpectedValueException
648
     */
649
    protected function getAttributeValue(object $object, string $attribute, ?string $format = null, array $context = []): mixed
650
    {
651
        $context['api_attribute'] = $attribute;
1,899✔
652
        $context['property_metadata'] = $propertyMetadata = $this->propertyMetadataFactory->create($context['resource_class'], $attribute, $this->getFactoryOptions($context));
1,899✔
653

654
        if ($context['api_denormalize'] ?? false) {
1,899✔
655
            return $this->propertyAccessor->getValue($object, $attribute);
30✔
656
        }
657

658
        $types = $propertyMetadata->getBuiltinTypes() ?? [];
1,899✔
659

660
        foreach ($types as $type) {
1,899✔
661
            if (
662
                $type->isCollection()
1,856✔
663
                && ($collectionValueType = $type->getCollectionValueTypes()[0] ?? null)
1,856✔
664
                && ($className = $collectionValueType->getClassName())
1,856✔
665
                && $this->resourceClassResolver->isResourceClass($className)
1,856✔
666
            ) {
667
                $childContext = $this->createChildContext($this->createOperationContext($context, $className), $attribute, $format);
615✔
668

669
                // @see ApiPlatform\Hal\Serializer\ItemNormalizer:getComponents logic for intentional duplicate content
670
                // @see ApiPlatform\JsonApi\Serializer\ItemNormalizer:getComponents logic for intentional duplicate content
671
                if ('jsonld' === $format && $itemUriTemplate = $propertyMetadata->getUriTemplate()) {
615✔
672
                    $operation = $this->resourceMetadataCollectionFactory->create($className)->getOperation(
3✔
673
                        operationName: $itemUriTemplate,
3✔
674
                        forceCollection: true,
3✔
675
                        httpOperation: true
3✔
676
                    );
3✔
677

678
                    return $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_PATH, $operation, $childContext);
3✔
679
                }
680

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

683
                if (!is_iterable($attributeValue)) {
612✔
684
                    throw new UnexpectedValueException('Unexpected non-iterable value for to-many relation.');
×
685
                }
686

687
                $resourceClass = $this->resourceClassResolver->getResourceClass($attributeValue, $className);
612✔
688

689
                $data = $this->normalizeCollectionOfRelations($propertyMetadata, $attributeValue, $resourceClass, $format, $childContext);
612✔
690
                $context['data'] = $data;
612✔
691
                $context['type'] = $type;
612✔
692

693
                if ($this->tagCollector) {
612✔
694
                    $this->tagCollector->collect($context);
554✔
695
                }
696

697
                return $data;
612✔
698
            }
699

700
            if (
701
                ($className = $type->getClassName())
1,856✔
702
                && $this->resourceClassResolver->isResourceClass($className)
1,856✔
703
            ) {
704
                $childContext = $this->createChildContext($this->createOperationContext($context, $className), $attribute, $format);
861✔
705
                unset($childContext['iri'], $childContext['uri_variables'], $childContext['item_uri_template']);
861✔
706
                if ('jsonld' === $format && $uriTemplate = $propertyMetadata->getUriTemplate()) {
861✔
707
                    $operation = $this->resourceMetadataCollectionFactory->create($className)->getOperation(
3✔
708
                        operationName: $uriTemplate,
3✔
709
                        httpOperation: true
3✔
710
                    );
3✔
711

712
                    return $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_PATH, $operation, $childContext);
3✔
713
                }
714

715
                $attributeValue = $this->propertyAccessor->getValue($object, $attribute);
858✔
716

717
                if (!\is_object($attributeValue) && null !== $attributeValue) {
852✔
718
                    throw new UnexpectedValueException('Unexpected non-object value for to-one relation.');
×
719
                }
720

721
                $resourceClass = $this->resourceClassResolver->getResourceClass($attributeValue, $className);
852✔
722

723
                $data = $this->normalizeRelation($propertyMetadata, $attributeValue, $resourceClass, $format, $childContext);
852✔
724
                $context['data'] = $data;
852✔
725
                $context['type'] = $type;
852✔
726

727
                if ($this->tagCollector) {
852✔
728
                    $this->tagCollector->collect($context);
803✔
729
                }
730

731
                return $data;
852✔
732
            }
733

734
            if (!$this->serializer instanceof NormalizerInterface) {
1,835✔
735
                throw new LogicException(\sprintf('The injected serializer must be an instance of "%s".', NormalizerInterface::class));
×
736
            }
737

738
            unset(
1,835✔
739
                $context['resource_class'],
1,835✔
740
                $context['force_resource_class'],
1,835✔
741
                $context['uri_variables'],
1,835✔
742
            );
1,835✔
743

744
            // Anonymous resources
745
            if ($className) {
1,835✔
746
                $childContext = $this->createChildContext($this->createOperationContext($context, $className), $attribute, $format);
566✔
747
                $childContext['output']['gen_id'] = $propertyMetadata->getGenId() ?? true;
566✔
748

749
                $attributeValue = $this->propertyAccessor->getValue($object, $attribute);
566✔
750

751
                return $this->serializer->normalize($attributeValue, $format, $childContext);
557✔
752
            }
753

754
            if ('array' === $type->getBuiltinType()) {
1,818✔
755
                if ($className = ($type->getCollectionValueTypes()[0] ?? null)?->getClassName()) {
542✔
756
                    $context = $this->createOperationContext($context, $className);
11✔
757
                }
758

759
                $childContext = $this->createChildContext($context, $attribute, $format);
542✔
760
                $childContext['output']['gen_id'] = $propertyMetadata->getGenId() ?? true;
542✔
761

762
                $attributeValue = $this->propertyAccessor->getValue($object, $attribute);
542✔
763

764
                return $this->serializer->normalize($attributeValue, $format, $childContext);
542✔
765
            }
766
        }
767

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

772
        unset(
1,858✔
773
            $context['resource_class'],
1,858✔
774
            $context['force_resource_class'],
1,858✔
775
            $context['uri_variables']
1,858✔
776
        );
1,858✔
777

778
        $attributeValue = $this->propertyAccessor->getValue($object, $attribute);
1,858✔
779

780
        return $this->serializer->normalize($attributeValue, $format, $context);
1,857✔
781
    }
782

783
    /**
784
     * Normalizes a collection of relations (to-many).
785
     *
786
     * @throws UnexpectedValueException
787
     */
788
    protected function normalizeCollectionOfRelations(ApiProperty $propertyMetadata, iterable $attributeValue, string $resourceClass, ?string $format, array $context): array
789
    {
790
        $value = [];
554✔
791
        foreach ($attributeValue as $index => $obj) {
554✔
792
            if (!\is_object($obj) && null !== $obj) {
147✔
793
                throw new UnexpectedValueException('Unexpected non-object element in to-many relation.');
×
794
            }
795

796
            // update context, if concrete object class deviates from general relation class (e.g. in case of polymorphic resources)
797
            $objResourceClass = $this->resourceClassResolver->getResourceClass($obj, $resourceClass);
147✔
798
            $context['resource_class'] = $objResourceClass;
147✔
799
            if ($this->resourceMetadataCollectionFactory) {
147✔
800
                $context['operation'] = $this->resourceMetadataCollectionFactory->create($objResourceClass)->getOperation();
147✔
801
            }
802

803
            $value[$index] = $this->normalizeRelation($propertyMetadata, $obj, $resourceClass, $format, $context);
147✔
804
        }
805

806
        return $value;
554✔
807
    }
808

809
    /**
810
     * Normalizes a relation.
811
     *
812
     * @throws LogicException
813
     * @throws UnexpectedValueException
814
     */
815
    protected function normalizeRelation(ApiProperty $propertyMetadata, ?object $relatedObject, string $resourceClass, ?string $format, array $context): \ArrayObject|array|string|null
816
    {
817
        if (null === $relatedObject || !empty($context['attributes']) || $propertyMetadata->isReadableLink()) {
751✔
818
            if (!$this->serializer instanceof NormalizerInterface) {
598✔
819
                throw new LogicException(\sprintf('The injected serializer must be an instance of "%s".', NormalizerInterface::class));
×
820
            }
821

822
            $relatedContext = $this->createOperationContext($context, $resourceClass);
598✔
823
            $normalizedRelatedObject = $this->serializer->normalize($relatedObject, $format, $relatedContext);
598✔
824
            if (!\is_string($normalizedRelatedObject) && !\is_array($normalizedRelatedObject) && !$normalizedRelatedObject instanceof \ArrayObject && null !== $normalizedRelatedObject) {
598✔
825
                throw new UnexpectedValueException('Expected normalized relation to be an IRI, array, \ArrayObject or null');
×
826
            }
827

828
            return $normalizedRelatedObject;
598✔
829
        }
830

831
        $context['iri'] = $iri = $this->iriConverter->getIriFromResource(resource: $relatedObject, context: $context);
238✔
832
        $context['data'] = $iri;
238✔
833
        $context['object'] = $relatedObject;
238✔
834
        unset($context['property_metadata'], $context['api_attribute']);
238✔
835

836
        if ($this->tagCollector) {
238✔
837
            $this->tagCollector->collect($context);
238✔
838
        } elseif (isset($context['resources'])) {
×
839
            $context['resources'][$iri] = $iri;
×
840
        }
841

842
        $push = $propertyMetadata->getPush() ?? false;
238✔
843
        if (isset($context['resources_to_push']) && $push) {
238✔
844
            $context['resources_to_push'][$iri] = $iri;
17✔
845
        }
846

847
        return $iri;
238✔
848
    }
849

850
    private function createAttributeValue(string $attribute, mixed $value, ?string $format = null, array &$context = []): mixed
851
    {
852
        try {
853
            return $this->createAndValidateAttributeValue($attribute, $value, $format, $context);
555✔
854
        } catch (NotNormalizableValueException $exception) {
41✔
855
            if (!isset($context['not_normalizable_value_exceptions'])) {
29✔
856
                throw $exception;
28✔
857
            }
858
            $context['not_normalizable_value_exceptions'][] = $exception;
1✔
859

860
            throw $exception;
1✔
861
        }
862
    }
863

864
    private function createAndValidateAttributeValue(string $attribute, mixed $value, ?string $format = null, array $context = []): mixed
865
    {
866
        $propertyMetadata = $this->propertyMetadataFactory->create($context['resource_class'], $attribute, $this->getFactoryOptions($context));
582✔
867
        $types = $propertyMetadata->getBuiltinTypes() ?? [];
582✔
868
        $isMultipleTypes = \count($types) > 1;
582✔
869

870
        foreach ($types as $type) {
582✔
871
            if (null === $value && ($type->isNullable() || ($context[static::DISABLE_TYPE_ENFORCEMENT] ?? false))) {
572✔
872
                return $value;
7✔
873
            }
874

875
            $collectionValueType = $type->getCollectionValueTypes()[0] ?? null;
571✔
876

877
            /* From @see AbstractObjectNormalizer::validateAndDenormalize() */
878
            // Fix a collection that contains the only one element
879
            // This is special to xml format only
880
            if ('xml' === $format && null !== $collectionValueType && (!\is_array($value) || !\is_int(key($value)))) {
571✔
881
                $value = [$value];
3✔
882
            }
883

884
            if (
885
                $type->isCollection()
571✔
886
                && null !== $collectionValueType
571✔
887
                && null !== ($className = $collectionValueType->getClassName())
571✔
888
                && $this->resourceClassResolver->isResourceClass($className)
571✔
889
            ) {
890
                $resourceClass = $this->resourceClassResolver->getResourceClass(null, $className);
44✔
891
                $context['resource_class'] = $resourceClass;
44✔
892
                unset($context['uri_variables']);
44✔
893

894
                return $this->denormalizeCollection($attribute, $propertyMetadata, $type, $resourceClass, $value, $format, $context);
44✔
895
            }
896

897
            if (
898
                null !== ($className = $type->getClassName())
559✔
899
                && $this->resourceClassResolver->isResourceClass($className)
559✔
900
            ) {
901
                $resourceClass = $this->resourceClassResolver->getResourceClass(null, $className);
150✔
902
                $childContext = $this->createChildContext($this->createOperationContext($context, $resourceClass), $attribute, $format);
150✔
903

904
                return $this->denormalizeRelation($attribute, $propertyMetadata, $resourceClass, $value, $format, $childContext);
150✔
905
            }
906

907
            if (
908
                $type->isCollection()
512✔
909
                && null !== $collectionValueType
512✔
910
                && null !== ($className = $collectionValueType->getClassName())
512✔
911
                && \is_array($value)
512✔
912
            ) {
913
                if (!$this->serializer instanceof DenormalizerInterface) {
9✔
914
                    throw new LogicException(\sprintf('The injected serializer must be an instance of "%s".', DenormalizerInterface::class));
×
915
                }
916

917
                unset($context['resource_class'], $context['uri_variables']);
9✔
918

919
                return $this->serializer->denormalize($value, $className.'[]', $format, $context);
9✔
920
            }
921

922
            if (null !== $className = $type->getClassName()) {
510✔
923
                if (!$this->serializer instanceof DenormalizerInterface) {
44✔
924
                    throw new LogicException(\sprintf('The injected serializer must be an instance of "%s".', DenormalizerInterface::class));
×
925
                }
926

927
                unset($context['resource_class'], $context['uri_variables']);
44✔
928

929
                return $this->serializer->denormalize($value, $className, $format, $context);
44✔
930
            }
931

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

941
                switch ($type->getBuiltinType()) {
45✔
942
                    case Type::BUILTIN_TYPE_BOOL:
45✔
943
                        // according to http://www.w3.org/TR/xmlschema-2/#boolean, valid representations are "false", "true", "0" and "1"
944
                        if ('false' === $value || '0' === $value) {
12✔
945
                            $value = false;
6✔
946
                        } elseif ('true' === $value || '1' === $value) {
6✔
947
                            $value = true;
6✔
948
                        } else {
949
                            // union/intersect types: try the next type, if not valid, an exception will be thrown at the end
950
                            if ($isMultipleTypes) {
×
951
                                break 2;
×
952
                            }
953
                            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);
×
954
                        }
955
                        break;
12✔
956
                    case Type::BUILTIN_TYPE_INT:
33✔
957
                        if (ctype_digit($value) || ('-' === $value[0] && ctype_digit(substr($value, 1)))) {
12✔
958
                            $value = (int) $value;
12✔
959
                        } else {
960
                            // union/intersect types: try the next type, if not valid, an exception will be thrown at the end
961
                            if ($isMultipleTypes) {
×
962
                                break 2;
×
963
                            }
964
                            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);
×
965
                        }
966
                        break;
12✔
967
                    case Type::BUILTIN_TYPE_FLOAT:
21✔
968
                        if (is_numeric($value)) {
12✔
969
                            return (float) $value;
3✔
970
                        }
971

972
                        switch ($value) {
973
                            case 'NaN':
9✔
974
                                return \NAN;
3✔
975
                            case 'INF':
6✔
976
                                return \INF;
3✔
977
                            case '-INF':
3✔
978
                                return -\INF;
3✔
979
                            default:
980
                                // union/intersect types: try the next type, if not valid, an exception will be thrown at the end
981
                                if ($isMultipleTypes) {
×
982
                                    break 3;
×
983
                                }
984
                                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);
×
985
                        }
986
                }
987
            }
988

989
            if ($context[static::DISABLE_TYPE_ENFORCEMENT] ?? false) {
485✔
990
                return $value;
×
991
            }
992

993
            try {
994
                $this->validateType($attribute, $type, $value, $format, $context);
485✔
995

996
                break;
473✔
997
            } catch (NotNormalizableValueException $e) {
21✔
998
                // union/intersect types: try the next type
999
                if (!$isMultipleTypes) {
21✔
1000
                    throw $e;
12✔
1001
                }
1002
            }
1003
        }
1004

1005
        return $value;
483✔
1006
    }
1007

1008
    /**
1009
     * Sets a value of the object using the PropertyAccess component.
1010
     */
1011
    private function setValue(object $object, string $attributeName, mixed $value): void
1012
    {
1013
        try {
1014
            $this->propertyAccessor->setValue($object, $attributeName, $value);
530✔
1015
        } catch (NoSuchPropertyException) {
25✔
1016
            // Properties not found are ignored
1017
        }
1018
    }
1019
}
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