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

api-platform / core / 9941154391

15 Jul 2024 02:20PM UTC coverage: 63.435% (+0.01%) from 63.421%
9941154391

push

github

web-flow
fix(jsonld): mitigate #6465 (#6469)

9 of 12 new or added lines in 1 file covered. (75.0%)

2 existing lines in 2 files now uncovered.

11181 of 17626 relevant lines covered (63.43%)

53.26 hits per line

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

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

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

12
declare(strict_types=1);
13

14
namespace ApiPlatform\Serializer;
15

16
use ApiPlatform\Api\IriConverterInterface as LegacyIriConverterInterface;
17
use ApiPlatform\Api\ResourceClassResolverInterface as LegacyResourceClassResolverInterface;
18
use ApiPlatform\Exception\InvalidArgumentException;
19
use ApiPlatform\Exception\ItemNotFoundException;
20
use ApiPlatform\Metadata\ApiProperty;
21
use ApiPlatform\Metadata\CollectionOperationInterface;
22
use ApiPlatform\Metadata\IriConverterInterface;
23
use ApiPlatform\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
24
use ApiPlatform\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
25
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
26
use ApiPlatform\Metadata\ResourceAccessCheckerInterface;
27
use ApiPlatform\Metadata\ResourceClassResolverInterface;
28
use ApiPlatform\Metadata\UrlGeneratorInterface;
29
use ApiPlatform\Metadata\Util\ClassInfoTrait;
30
use ApiPlatform\Metadata\Util\CloneTrait;
31
use Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException;
32
use Symfony\Component\PropertyAccess\PropertyAccess;
33
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
34
use Symfony\Component\PropertyInfo\Type;
35
use Symfony\Component\Serializer\Encoder\CsvEncoder;
36
use Symfony\Component\Serializer\Encoder\XmlEncoder;
37
use Symfony\Component\Serializer\Exception\LogicException;
38
use Symfony\Component\Serializer\Exception\MissingConstructorArgumentsException;
39
use Symfony\Component\Serializer\Exception\NotNormalizableValueException;
40
use Symfony\Component\Serializer\Exception\RuntimeException;
41
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
42
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
43
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
44
use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer;
45
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
46
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
47
use Symfony\Component\Serializer\Serializer;
48

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

62
    protected PropertyAccessorInterface $propertyAccessor;
63
    protected array $localCache = [];
64
    protected array $localFactoryOptionsCache = [];
65
    protected ?ResourceAccessCheckerInterface $resourceAccessChecker;
66

67
    public function __construct(protected PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, protected PropertyMetadataFactoryInterface $propertyMetadataFactory, protected LegacyIriConverterInterface|IriConverterInterface $iriConverter, protected LegacyResourceClassResolverInterface|ResourceClassResolverInterface $resourceClassResolver, ?PropertyAccessorInterface $propertyAccessor = null, ?NameConverterInterface $nameConverter = null, ?ClassMetadataFactoryInterface $classMetadataFactory = null, array $defaultContext = [], ?ResourceMetadataCollectionFactoryInterface $resourceMetadataCollectionFactory = null, ?ResourceAccessCheckerInterface $resourceAccessChecker = null, protected ?TagCollectorInterface $tagCollector = null)
68
    {
69
        if (!isset($defaultContext['circular_reference_handler'])) {
331✔
70
            $defaultContext['circular_reference_handler'] = fn ($object): ?string => $this->iriConverter->getIriFromResource($object);
331✔
71
        }
72

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

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

88
        $class = $context['force_resource_class'] ?? $this->getObjectClass($data);
191✔
89
        if (($context['output']['class'] ?? null) === $class) {
191✔
90
            return true;
16✔
91
        }
92

93
        return $this->resourceClassResolver->isResourceClass($class);
175✔
94
    }
95

96
    public function getSupportedTypes(?string $format): array
97
    {
98
        return [
223✔
99
            'object' => true,
223✔
100
        ];
223✔
101
    }
102

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

117
        return true;
×
118
    }
119

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

133
            unset($context['output'], $context['operation'], $context['operation_name']);
16✔
134
            $context['resource_class'] = $outputClass;
16✔
135
            $context['api_sub_level'] = true;
16✔
136
            $context[self::ALLOW_EXTRA_ATTRIBUTES] = false;
16✔
137

138
            return $this->serializer->normalize($object, $format, $context);
16✔
139
        }
140

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

147
        if ($this->resourceClassResolver->isResourceClass($resourceClass)) {
215✔
148
            $context = $this->initContext($resourceClass, $context);
199✔
149
        }
150

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

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

167
        if (!$this->tagCollector && isset($context['resources'])) {
215✔
168
            $context['resources'][$iri] = $iri;
×
169
        }
170

171
        $context['object'] = $object;
215✔
172
        $context['format'] = $format;
215✔
173

174
        $data = parent::normalize($object, $format, $context);
215✔
175

176
        $context['data'] = $data;
211✔
177
        unset($context['property_metadata'], $context['api_attribute']);
211✔
178

179
        if ($emptyResourceAsIri && \is_array($data) && 0 === \count($data)) {
211✔
180
            $context['data'] = $iri;
×
181

182
            if ($this->tagCollector) {
×
183
                $this->tagCollector->collect($context);
×
184
            }
185

186
            return $iri;
×
187
        }
188

189
        if ($this->tagCollector) {
211✔
190
            $this->tagCollector->collect($context);
180✔
191
        }
192

193
        return $data;
211✔
194
    }
195

196
    /**
197
     * {@inheritdoc}
198
     */
199
    public function supportsDenormalization(mixed $data, string $type, ?string $format = null, array $context = []): bool
200
    {
201
        if (($context['input']['class'] ?? null) === $type) {
12✔
202
            return true;
×
203
        }
204

205
        return $this->localCache[$type] ?? $this->localCache[$type] = $this->resourceClassResolver->isResourceClass($type);
12✔
206
    }
207

208
    /**
209
     * {@inheritdoc}
210
     */
211
    public function denormalize(mixed $data, string $class, ?string $format = null, array $context = []): mixed
212
    {
213
        $resourceClass = $class;
28✔
214

215
        if ($inputClass = $this->getInputClass($context)) {
28✔
216
            if (!$this->serializer instanceof DenormalizerInterface) {
×
217
                throw new LogicException('Cannot denormalize the input because the injected serializer is not a denormalizer');
×
218
            }
219

220
            unset($context['input'], $context['operation'], $context['operation_name'], $context['uri_variables']);
×
221
            $context['resource_class'] = $inputClass;
×
222

223
            try {
224
                return $this->serializer->denormalize($data, $inputClass, $format, $context);
×
225
            } catch (NotNormalizableValueException $e) {
×
226
                throw new UnexpectedValueException('The input data is misformatted.', $e->getCode(), $e);
×
227
            }
228
        }
229

230
        if (null === $objectToPopulate = $this->extractObjectToPopulate($resourceClass, $context, static::OBJECT_TO_POPULATE)) {
28✔
231
            $normalizedData = \is_scalar($data) ? [$data] : $this->prepareForDenormalization($data);
28✔
232
            $class = $this->getClassDiscriminatorResolvedClass($normalizedData, $class, $context);
28✔
233
        }
234

235
        $context['api_denormalize'] = true;
28✔
236

237
        if ($this->resourceClassResolver->isResourceClass($class)) {
28✔
238
            $resourceClass = $this->resourceClassResolver->getResourceClass($objectToPopulate, $class);
28✔
239
            $context['resource_class'] = $resourceClass;
28✔
240
        }
241

242
        if (\is_string($data)) {
28✔
243
            try {
244
                return $this->iriConverter->getResourceFromIri($data, $context + ['fetch_data' => true]);
×
245
            } catch (ItemNotFoundException $e) {
×
246
                throw new UnexpectedValueException($e->getMessage(), $e->getCode(), $e);
×
247
            } catch (InvalidArgumentException $e) {
×
248
                throw new UnexpectedValueException(sprintf('Invalid IRI "%s".', $data), $e->getCode(), $e);
×
249
            }
250
        }
251

252
        if (!\is_array($data)) {
28✔
253
            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);
×
254
        }
255

256
        $previousObject = $this->clone($objectToPopulate);
28✔
257
        $object = parent::denormalize($data, $class, $format, $context);
28✔
258

259
        if (!$this->resourceClassResolver->isResourceClass($class)) {
16✔
260
            return $object;
×
261
        }
262

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

269
        $options = $this->getFactoryOptions($context);
16✔
270
        $propertyNames = iterator_to_array($this->propertyNameCollectionFactory->create($resourceClass, $options));
16✔
271

272
        // Revert attributes that aren't allowed to be changed after a post-denormalize check
273
        foreach (array_keys($data) as $attribute) {
16✔
274
            $attribute = $this->nameConverter ? $this->nameConverter->denormalize((string) $attribute) : $attribute;
16✔
275
            if (!\in_array($attribute, $propertyNames, true)) {
16✔
276
                continue;
×
277
            }
278

279
            if (!$this->canAccessAttributePostDenormalize($object, $previousObject, $attribute, $context)) {
16✔
280
                if (null !== $previousObject) {
×
281
                    $this->setValue($object, $attribute, $this->propertyAccessor->getValue($previousObject, $attribute));
×
282
                } else {
283
                    $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $attribute, $options);
×
284
                    $this->setValue($object, $attribute, $propertyMetadata->getDefault());
×
285
                }
286
            }
287
        }
288

289
        return $object;
16✔
290
    }
291

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

305
            return $object;
×
306
        }
307

308
        $class = $this->getClassDiscriminatorResolvedClass($data, $class, $context);
28✔
309
        $reflectionClass = new \ReflectionClass($class);
28✔
310

311
        $constructor = $this->getConstructor($data, $class, $context, $reflectionClass, $allowedAttributes);
28✔
312
        if ($constructor) {
28✔
313
            $constructorParameters = $constructor->getParameters();
28✔
314

315
            $params = [];
28✔
316
            $missingConstructorArguments = [];
28✔
317
            foreach ($constructorParameters as $constructorParameter) {
28✔
318
                $paramName = $constructorParameter->name;
×
319
                $key = $this->nameConverter ? $this->nameConverter->normalize($paramName, $class, $format, $context) : $paramName;
×
320

321
                $allowed = false === $allowedAttributes || (\is_array($allowedAttributes) && \in_array($paramName, $allowedAttributes, true));
×
322
                $ignored = !$this->isAllowedAttribute($class, $paramName, $format, $context);
×
323
                if ($constructorParameter->isVariadic()) {
×
324
                    if ($allowed && !$ignored && (isset($data[$key]) || \array_key_exists($key, $data))) {
×
325
                        if (!\is_array($data[$paramName])) {
×
326
                            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));
×
327
                        }
328

329
                        $params[] = $data[$paramName];
×
330
                    }
331
                } elseif ($allowed && !$ignored && (isset($data[$key]) || \array_key_exists($key, $data))) {
×
332
                    $constructorContext = $context;
×
333
                    $constructorContext['deserialization_path'] = $context['deserialization_path'] ?? $key;
×
334
                    try {
335
                        $params[] = $this->createConstructorArgument($data[$key], $key, $constructorParameter, $constructorContext, $format);
×
336
                    } catch (NotNormalizableValueException $exception) {
×
337
                        if (!isset($context['not_normalizable_value_exceptions'])) {
×
338
                            throw $exception;
×
339
                        }
340
                        $context['not_normalizable_value_exceptions'][] = $exception;
×
341
                    }
342

343
                    // Don't run set for a parameter passed to the constructor
344
                    unset($data[$key]);
×
345
                } elseif (isset($context[static::DEFAULT_CONSTRUCTOR_ARGUMENTS][$class][$key])) {
×
346
                    $params[] = $context[static::DEFAULT_CONSTRUCTOR_ARGUMENTS][$class][$key];
×
347
                } elseif ($constructorParameter->isDefaultValueAvailable()) {
×
348
                    $params[] = $constructorParameter->getDefaultValue();
×
349
                } else {
350
                    if (!isset($context['not_normalizable_value_exceptions'])) {
×
351
                        $missingConstructorArguments[] = $constructorParameter->name;
×
352
                    }
353

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

359
            if ($missingConstructorArguments) {
28✔
360
                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);
×
361
            }
362

363
            if (\count($context['not_normalizable_value_exceptions'] ?? []) > 0) {
28✔
364
                return $reflectionClass->newInstanceWithoutConstructor();
×
365
            }
366

367
            if ($constructor->isConstructor()) {
28✔
368
                return $reflectionClass->newInstanceArgs($params);
28✔
369
            }
370

371
            return $constructor->invokeArgs(null, $params);
×
372
        }
373

374
        return new $class();
×
375
    }
376

377
    protected function getClassDiscriminatorResolvedClass(array $data, string $class, array $context = []): string
378
    {
379
        if (null === $this->classDiscriminatorResolver || (null === $mapping = $this->classDiscriminatorResolver->getMappingForClass($class))) {
28✔
380
            return $class;
28✔
381
        }
382

383
        if (!isset($data[$mapping->getTypeProperty()])) {
×
384
            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());
×
385
        }
386

387
        $type = $data[$mapping->getTypeProperty()];
×
388
        if (null === ($mappedClass = $mapping->getClassForType($type))) {
×
389
            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);
×
390
        }
391

392
        return $mappedClass;
×
393
    }
394

395
    protected function createConstructorArgument($parameterData, string $key, \ReflectionParameter $constructorParameter, array &$context, ?string $format = null): mixed
396
    {
397
        return $this->createAndValidateAttributeValue($constructorParameter->name, $parameterData, $format, $context);
×
398
    }
399

400
    /**
401
     * {@inheritdoc}
402
     *
403
     * Unused in this context.
404
     *
405
     * @return string[]
406
     */
407
    protected function extractAttributes($object, $format = null, array $context = []): array
408
    {
409
        return [];
×
410
    }
411

412
    /**
413
     * {@inheritdoc}
414
     */
415
    protected function getAllowedAttributes(string|object $classOrObject, array $context, bool $attributesAsString = false): array|bool
416
    {
417
        if (!$this->resourceClassResolver->isResourceClass($context['resource_class'])) {
227✔
418
            return parent::getAllowedAttributes($classOrObject, $context, $attributesAsString);
16✔
419
        }
420

421
        $resourceClass = $this->resourceClassResolver->getResourceClass(null, $context['resource_class']); // fix for abstract classes and interfaces
211✔
422
        $options = $this->getFactoryOptions($context);
211✔
423
        $propertyNames = $this->propertyNameCollectionFactory->create($resourceClass, $options);
211✔
424

425
        $allowedAttributes = [];
211✔
426
        foreach ($propertyNames as $propertyName) {
211✔
427
            $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $propertyName, $options);
211✔
428

429
            if (
430
                $this->isAllowedAttribute($classOrObject, $propertyName, null, $context)
211✔
431
                && (isset($context['api_normalize']) && $propertyMetadata->isReadable()
211✔
432
                    || isset($context['api_denormalize']) && ($propertyMetadata->isWritable() || !\is_object($classOrObject) && $propertyMetadata->isInitializable())
211✔
433
                )
434
            ) {
435
                $allowedAttributes[] = $propertyName;
199✔
436
            }
437
        }
438

439
        return $allowedAttributes;
211✔
440
    }
441

442
    /**
443
     * {@inheritdoc}
444
     */
445
    protected function isAllowedAttribute(object|string $classOrObject, string $attribute, ?string $format = null, array $context = []): bool
446
    {
447
        if (!parent::isAllowedAttribute($classOrObject, $attribute, $format, $context)) {
227✔
448
            return false;
4✔
449
        }
450

451
        return $this->canAccessAttribute(\is_object($classOrObject) ? $classOrObject : null, $attribute, $context);
227✔
452
    }
453

454
    /**
455
     * Check if access to the attribute is granted.
456
     */
457
    protected function canAccessAttribute(?object $object, string $attribute, array $context = []): bool
458
    {
459
        if (!$this->resourceClassResolver->isResourceClass($context['resource_class'])) {
227✔
460
            return true;
16✔
461
        }
462

463
        $options = $this->getFactoryOptions($context);
211✔
464
        $propertyMetadata = $this->propertyMetadataFactory->create($context['resource_class'], $attribute, $options);
211✔
465
        $security = $propertyMetadata->getSecurity();
211✔
466
        if (null !== $this->resourceAccessChecker && $security) {
211✔
467
            return $this->resourceAccessChecker->isGranted($context['resource_class'], $security, [
×
468
                'object' => $object,
×
469
                'property' => $attribute,
×
470
            ]);
×
471
        }
472

473
        return true;
211✔
474
    }
475

476
    /**
477
     * Check if access to the attribute is granted.
478
     */
479
    protected function canAccessAttributePostDenormalize(?object $object, ?object $previousObject, string $attribute, array $context = []): bool
480
    {
481
        $options = $this->getFactoryOptions($context);
16✔
482
        $propertyMetadata = $this->propertyMetadataFactory->create($context['resource_class'], $attribute, $options);
16✔
483
        $security = $propertyMetadata->getSecurityPostDenormalize();
16✔
484
        if ($this->resourceAccessChecker && $security) {
16✔
485
            return $this->resourceAccessChecker->isGranted($context['resource_class'], $security, [
×
486
                'object' => $object,
×
487
                'previous_object' => $previousObject,
×
488
                'property' => $attribute,
×
489
            ]);
×
490
        }
491

492
        return true;
16✔
493
    }
494

495
    /**
496
     * {@inheritdoc}
497
     */
498
    protected function setAttributeValue(object $object, string $attribute, mixed $value, ?string $format = null, array $context = []): void
499
    {
500
        try {
501
            $this->setValue($object, $attribute, $this->createAttributeValue($attribute, $value, $format, $context));
28✔
502
        } catch (NotNormalizableValueException $exception) {
12✔
503
            // Only throw if collecting denormalization errors is disabled.
504
            if (!isset($context['not_normalizable_value_exceptions'])) {
8✔
505
                throw $exception;
8✔
506
            }
507
        }
508
    }
509

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

524
        if (!$isValid) {
16✔
525
            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);
×
526
        }
527
    }
528

529
    /**
530
     * Denormalizes a collection of objects.
531
     *
532
     * @throws NotNormalizableValueException
533
     */
534
    protected function denormalizeCollection(string $attribute, ApiProperty $propertyMetadata, Type $type, string $className, mixed $value, ?string $format, array $context): array
535
    {
536
        if (!\is_array($value)) {
12✔
537
            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✔
538
        }
539

540
        $values = [];
8✔
541
        $childContext = $this->createChildContext($this->createOperationContext($context, $className), $attribute, $format);
8✔
542
        $collectionKeyTypes = $type->getCollectionKeyTypes();
8✔
543
        foreach ($value as $index => $obj) {
8✔
544
            // no typehint provided on collection key
545
            if (!$collectionKeyTypes) {
8✔
546
                $values[$index] = $this->denormalizeRelation($attribute, $propertyMetadata, $className, $obj, $format, $childContext);
×
547
                continue;
×
548
            }
549

550
            // validate collection key typehint
551
            foreach ($collectionKeyTypes as $collectionKeyType) {
8✔
552
                $collectionKeyBuiltinType = $collectionKeyType->getBuiltinType();
8✔
553
                if (!\call_user_func('is_'.$collectionKeyBuiltinType, $index)) {
8✔
554
                    continue;
4✔
555
                }
556

557
                $values[$index] = $this->denormalizeRelation($attribute, $propertyMetadata, $className, $obj, $format, $childContext);
4✔
558
                continue 2;
4✔
559
            }
560
            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);
4✔
561
        }
562

563
        return $values;
4✔
564
    }
565

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

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

607
                return null;
×
608
            }
609
        }
610

611
        if ($propertyMetadata->isWritableLink()) {
×
612
            $context['api_allow_update'] = true;
×
613

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

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

623
            return $item;
×
624
        }
625

626
        if (!\is_array($value)) {
×
627
            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);
×
628
        }
629

630
        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);
×
631
    }
632

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

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

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

660
        return $options + $this->localFactoryOptionsCache[$operationCacheKey.$suffix] = $options;
227✔
661
    }
662

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

673
        if ($context['api_denormalize'] ?? false) {
199✔
674
            return $this->propertyAccessor->getValue($object, $attribute);
×
675
        }
676

677
        $types = $propertyMetadata->getBuiltinTypes() ?? [];
199✔
678

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

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

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

700
                $attributeValue = $this->propertyAccessor->getValue($object, $attribute);
24✔
701

702
                if (!is_iterable($attributeValue)) {
24✔
703
                    throw new UnexpectedValueException('Unexpected non-iterable value for to-many relation.');
×
704
                }
705

706
                $resourceClass = $this->resourceClassResolver->getResourceClass($attributeValue, $className);
24✔
707

708
                $data = $this->normalizeCollectionOfRelations($propertyMetadata, $attributeValue, $resourceClass, $format, $childContext);
24✔
709
                $context['data'] = $data;
24✔
710
                $context['type'] = $type;
24✔
711

712
                if ($this->tagCollector) {
24✔
713
                    $this->tagCollector->collect($context);
24✔
714
                }
715

716
                return $data;
24✔
717
            }
718

719
            if (
720
                ($className = $type->getClassName())
187✔
721
                && $this->resourceClassResolver->isResourceClass($className)
187✔
722
            ) {
723
                $childContext = $this->createChildContext($this->createOperationContext($context, $className), $attribute, $format);
24✔
724
                unset($childContext['iri'], $childContext['uri_variables'], $childContext['item_uri_template']);
24✔
725

726
                if ('jsonld' === $format && $uriTemplate = $propertyMetadata->getUriTemplate()) {
24✔
727
                    $operation = $this->resourceMetadataCollectionFactory->create($className)->getOperation(
×
728
                        operationName: $uriTemplate,
×
729
                        httpOperation: true
×
730
                    );
×
731

732
                    return $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_PATH, $operation, $childContext);
×
733
                }
734

735
                $attributeValue = $this->propertyAccessor->getValue($object, $attribute);
24✔
736

737
                if (!\is_object($attributeValue) && null !== $attributeValue) {
24✔
738
                    throw new UnexpectedValueException('Unexpected non-object value for to-one relation.');
×
739
                }
740

741
                $resourceClass = $this->resourceClassResolver->getResourceClass($attributeValue, $className);
24✔
742

743
                $data = $this->normalizeRelation($propertyMetadata, $attributeValue, $resourceClass, $format, $childContext);
24✔
744
                $context['data'] = $data;
24✔
745
                $context['type'] = $type;
24✔
746

747
                if ($this->tagCollector) {
24✔
748
                    $this->tagCollector->collect($context);
12✔
749
                }
750

751
                return $data;
24✔
752
            }
753

754
            if (!$this->serializer instanceof NormalizerInterface) {
187✔
755
                throw new LogicException(sprintf('The injected serializer must be an instance of "%s".', NormalizerInterface::class));
×
756
            }
757

758
            unset(
187✔
759
                $context['resource_class'],
187✔
760
                $context['force_resource_class'],
187✔
761
                $context['uri_variables'],
187✔
762
            );
187✔
763

764
            // Anonymous resources
765
            if ($className) {
187✔
766
                $childContext = $this->createChildContext($this->createOperationContext($context, $className), $attribute, $format);
67✔
767
                $childContext['output']['gen_id'] = $propertyMetadata->getGenId() ?? true;
67✔
768

769
                $attributeValue = $this->propertyAccessor->getValue($object, $attribute);
67✔
770

771
                return $this->serializer->normalize($attributeValue, $format, $childContext);
67✔
772
            }
773

774
            if ('array' === $type->getBuiltinType()) {
183✔
775
                if ($className = ($type->getCollectionValueTypes()[0] ?? null)?->getClassName()) {
36✔
776
                    $context = $this->createOperationContext($context, $className);
4✔
777
                }
778

779
                $childContext = $this->createChildContext($context, $attribute, $format);
36✔
780
                $childContext['output']['gen_id'] = $propertyMetadata->getGenId() ?? true;
36✔
781

782
                $attributeValue = $this->propertyAccessor->getValue($object, $attribute);
36✔
783

784
                return $this->serializer->normalize($attributeValue, $format, $childContext);
36✔
785
            }
786
        }
787

788
        if (!$this->serializer instanceof NormalizerInterface) {
195✔
789
            throw new LogicException(sprintf('The injected serializer must be an instance of "%s".', NormalizerInterface::class));
×
790
        }
791

792
        unset(
195✔
793
            $context['resource_class'],
195✔
794
            $context['force_resource_class'],
195✔
795
            $context['uri_variables']
195✔
796
        );
195✔
797

798
        $attributeValue = $this->propertyAccessor->getValue($object, $attribute);
195✔
799

800
        return $this->serializer->normalize($attributeValue, $format, $context);
191✔
801
    }
802

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

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

823
            $value[$index] = $this->normalizeRelation($propertyMetadata, $obj, $resourceClass, $format, $context);
×
824
        }
825

826
        return $value;
24✔
827
    }
828

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

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

848
            return $normalizedRelatedObject;
16✔
849
        }
850

851
        $context['iri'] = $iri = $this->iriConverter->getIriFromResource(resource: $relatedObject, context: $context);
8✔
852
        $context['data'] = $iri;
8✔
853
        $context['object'] = $relatedObject;
8✔
854
        unset($context['property_metadata'], $context['api_attribute']);
8✔
855

856
        if ($this->tagCollector) {
8✔
857
            $this->tagCollector->collect($context);
×
858
        } elseif (isset($context['resources'])) {
8✔
859
            $context['resources'][$iri] = $iri;
×
860
        }
861

862
        $push = $propertyMetadata->getPush() ?? false;
8✔
863
        if (isset($context['resources_to_push']) && $push) {
8✔
864
            $context['resources_to_push'][$iri] = $iri;
×
865
        }
866

867
        return $iri;
8✔
868
    }
869

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

880
            throw $exception;
×
881
        }
882
    }
883

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

890
        foreach ($types as $type) {
28✔
891
            if (null === $value && ($type->isNullable() || ($context[static::DISABLE_TYPE_ENFORCEMENT] ?? false))) {
28✔
892
                return $value;
×
893
            }
894

895
            $collectionValueType = $type->getCollectionValueTypes()[0] ?? null;
28✔
896

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

904
            if (
905
                $type->isCollection()
28✔
906
                && null !== $collectionValueType
28✔
907
                && null !== ($className = $collectionValueType->getClassName())
28✔
908
                && $this->resourceClassResolver->isResourceClass($className)
28✔
909
            ) {
910
                $resourceClass = $this->resourceClassResolver->getResourceClass(null, $className);
12✔
911
                $context['resource_class'] = $resourceClass;
12✔
912
                unset($context['uri_variables']);
12✔
913

914
                return $this->denormalizeCollection($attribute, $propertyMetadata, $type, $resourceClass, $value, $format, $context);
12✔
915
            }
916

917
            if (
918
                null !== ($className = $type->getClassName())
20✔
919
                && $this->resourceClassResolver->isResourceClass($className)
20✔
920
            ) {
921
                $resourceClass = $this->resourceClassResolver->getResourceClass(null, $className);
8✔
922
                $childContext = $this->createChildContext($this->createOperationContext($context, $resourceClass), $attribute, $format);
8✔
923

924
                return $this->denormalizeRelation($attribute, $propertyMetadata, $resourceClass, $value, $format, $childContext);
8✔
925
            }
926

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

NEW
937
                unset($context['resource_class'], $context['uri_variables']);
×
938

939
                return $this->serializer->denormalize($value, $className.'[]', $format, $context);
×
940
            }
941

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

NEW
947
                unset($context['resource_class'], $context['uri_variables']);
×
948

949
                return $this->serializer->denormalize($value, $className, $format, $context);
×
950
            }
951

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

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

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

1009
            if ($context[static::DISABLE_TYPE_ENFORCEMENT] ?? false) {
16✔
1010
                return $value;
×
1011
            }
1012

1013
            try {
1014
                $this->validateType($attribute, $type, $value, $format, $context);
16✔
1015

1016
                break;
16✔
1017
            } catch (NotNormalizableValueException $e) {
×
1018
                // union/intersect types: try the next type
1019
                if (!$isMultipleTypes) {
×
1020
                    throw $e;
×
1021
                }
1022
            }
1023
        }
1024

1025
        return $value;
16✔
1026
    }
1027

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