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

api-platform / core / 9710836697

28 Jun 2024 09:35AM UTC coverage: 63.285% (+1.2%) from 62.122%
9710836697

push

github

soyuka
docs: changelog v3.3.7

11104 of 17546 relevant lines covered (63.29%)

52.26 hits per line

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

55.7
/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'])) {
319✔
70
            $defaultContext['circular_reference_handler'] = fn ($object): ?string => $this->iriConverter->getIriFromResource($object);
319✔
71
        }
72

73
        parent::__construct($classMetadataFactory, $nameConverter, null, null, \Closure::fromCallable($this->getObjectClass(...)), $defaultContext);
319✔
74
        $this->propertyAccessor = $propertyAccessor ?: PropertyAccess::createPropertyAccessor();
319✔
75
        $this->resourceAccessChecker = $resourceAccessChecker;
319✔
76
        $this->resourceMetadataCollectionFactory = $resourceMetadataCollectionFactory;
319✔
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)) {
211✔
85
            return false;
68✔
86
        }
87

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

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

96
    public function getSupportedTypes(?string $format): array
97
    {
98
        return [
219✔
99
            'object' => true,
219✔
100
        ];
219✔
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);
211✔
128
        if ($outputClass = $this->getOutputClass($context)) {
211✔
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) {
211✔
144
            unset($context['operation_name']);
×
145
            unset($context['operation']);
×
146
            unset($context['iri']);
×
147
        }
148

149
        if ($this->resourceClassResolver->isResourceClass($resourceClass)) {
211✔
150
            $context = $this->initContext($resourceClass, $context);
195✔
151
        }
152

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

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

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

173
        $context['object'] = $object;
211✔
174
        $context['format'] = $format;
211✔
175

176
        $data = parent::normalize($object, $format, $context);
211✔
177

178
        $context['data'] = $data;
207✔
179
        unset($context['property_metadata']);
207✔
180
        unset($context['api_attribute']);
207✔
181

182
        if ($emptyResourceAsIri && \is_array($data) && 0 === \count($data)) {
207✔
183
            $context['data'] = $iri;
×
184

185
            if ($this->tagCollector) {
×
186
                $this->tagCollector->collect($context);
×
187
            }
188

189
            return $iri;
×
190
        }
191

192
        if ($this->tagCollector) {
207✔
193
            $this->tagCollector->collect($context);
176✔
194
        }
195

196
        return $data;
207✔
197
    }
198

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

208
        return $this->localCache[$type] ?? $this->localCache[$type] = $this->resourceClassResolver->isResourceClass($type);
12✔
209
    }
210

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

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

223
            unset($context['input'], $context['operation'], $context['operation_name']);
×
224
            $context['resource_class'] = $inputClass;
×
225

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

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

238
        $context['api_denormalize'] = true;
28✔
239

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

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

255
        if (!\is_array($data)) {
28✔
256
            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);
×
257
        }
258

259
        $previousObject = $this->clone($objectToPopulate);
28✔
260
        $object = parent::denormalize($data, $class, $format, $context);
28✔
261

262
        if (!$this->resourceClassResolver->isResourceClass($class)) {
16✔
263
            return $object;
×
264
        }
265

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

272
        $options = $this->getFactoryOptions($context);
16✔
273
        $propertyNames = iterator_to_array($this->propertyNameCollectionFactory->create($resourceClass, $options));
16✔
274

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

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

292
        return $object;
16✔
293
    }
294

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

308
            return $object;
×
309
        }
310

311
        $class = $this->getClassDiscriminatorResolvedClass($data, $class, $context);
28✔
312
        $reflectionClass = new \ReflectionClass($class);
28✔
313

314
        $constructor = $this->getConstructor($data, $class, $context, $reflectionClass, $allowedAttributes);
28✔
315
        if ($constructor) {
28✔
316
            $constructorParameters = $constructor->getParameters();
28✔
317

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

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

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

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

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

362
            if ($missingConstructorArguments) {
28✔
363
                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);
×
364
            }
365

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

370
            if ($constructor->isConstructor()) {
28✔
371
                return $reflectionClass->newInstanceArgs($params);
28✔
372
            }
373

374
            return $constructor->invokeArgs(null, $params);
×
375
        }
376

377
        return new $class();
×
378
    }
379

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

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

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

395
        return $mappedClass;
×
396
    }
397

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

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

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

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

428
        $allowedAttributes = [];
207✔
429
        foreach ($propertyNames as $propertyName) {
207✔
430
            $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $propertyName, $options);
207✔
431

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

442
        return $allowedAttributes;
207✔
443
    }
444

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

454
        return $this->canAccessAttribute(\is_object($classOrObject) ? $classOrObject : null, $attribute, $context);
223✔
455
    }
456

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

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

476
        return true;
207✔
477
    }
478

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

495
        return true;
16✔
496
    }
497

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

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

527
        if (!$isValid) {
16✔
528
            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);
×
529
        }
530
    }
531

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

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

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

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

566
        return $values;
4✔
567
    }
568

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

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

610
                return null;
×
611
            }
612
        }
613

614
        if ($propertyMetadata->isWritableLink()) {
×
615
            $context['api_allow_update'] = true;
×
616

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

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

626
            return $item;
×
627
        }
628

629
        if (!\is_array($value)) {
×
630
            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);
×
631
        }
632

633
        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);
×
634
    }
635

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

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

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

663
        return $options + $this->localFactoryOptionsCache[$operationCacheKey.$suffix] = $options;
223✔
664
    }
665

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

676
        if ($context['api_denormalize'] ?? false) {
195✔
677
            return $this->propertyAccessor->getValue($object, $attribute);
×
678
        }
679

680
        $types = $propertyMetadata->getBuiltinTypes() ?? [];
195✔
681

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

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

700
                    return $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_PATH, $operation, $childContext);
×
701
                }
702

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

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

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

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

715
                if ($this->tagCollector) {
24✔
716
                    $this->tagCollector->collect($context);
24✔
717
                }
718

719
                return $data;
24✔
720
            }
721

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

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

735
                    return $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_PATH, $operation, $childContext);
×
736
                }
737

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

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

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

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

750
                if ($this->tagCollector) {
24✔
751
                    $this->tagCollector->collect($context);
12✔
752
                }
753

754
                return $data;
24✔
755
            }
756

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

761
            unset(
183✔
762
                $context['resource_class'],
183✔
763
                $context['force_resource_class'],
183✔
764
            );
183✔
765

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

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

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

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

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

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

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

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

794
        unset($context['resource_class']);
191✔
795
        unset($context['force_resource_class']);
191✔
796

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

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

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

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

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

825
        return $value;
24✔
826
    }
827

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

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

847
            return $normalizedRelatedObject;
16✔
848
        }
849

850
        $context['iri'] = $iri = $this->iriConverter->getIriFromResource(resource: $relatedObject, context: $context);
8✔
851
        $context['data'] = $iri;
8✔
852
        $context['object'] = $relatedObject;
8✔
853
        unset($context['property_metadata']);
8✔
854
        unset($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

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

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

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

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

936
                unset($context['resource_class']);
×
937

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

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

946
                unset($context['resource_class']);
×
947

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

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

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

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

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

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

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

1024
        return $value;
16✔
1025
    }
1026

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