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

api-platform / core / 14726067612

29 Apr 2025 07:47AM UTC coverage: 23.443% (+15.2%) from 8.252%
14726067612

push

github

web-flow
feat(symfony): Autoconfigure classes using `#[ApiResource]` attribute (#6943)

0 of 12 new or added lines in 4 files covered. (0.0%)

3578 existing lines in 159 files now uncovered.

11517 of 49127 relevant lines covered (23.44%)

54.29 hits per line

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

84.85
/src/Hal/Serializer/ItemNormalizer.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\Hal\Serializer;
15

16
use ApiPlatform\Metadata\IriConverterInterface;
17
use ApiPlatform\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
18
use ApiPlatform\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
19
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
20
use ApiPlatform\Metadata\ResourceAccessCheckerInterface;
21
use ApiPlatform\Metadata\ResourceClassResolverInterface;
22
use ApiPlatform\Metadata\UrlGeneratorInterface;
23
use ApiPlatform\Metadata\Util\ClassInfoTrait;
24
use ApiPlatform\Serializer\AbstractItemNormalizer;
25
use ApiPlatform\Serializer\CacheKeyTrait;
26
use ApiPlatform\Serializer\ContextTrait;
27
use ApiPlatform\Serializer\TagCollectorInterface;
28
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
29
use Symfony\Component\PropertyInfo\PropertyInfoExtractor;
30
use Symfony\Component\PropertyInfo\Type as LegacyType;
31
use Symfony\Component\Serializer\Exception\CircularReferenceException;
32
use Symfony\Component\Serializer\Exception\LogicException;
33
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
34
use Symfony\Component\Serializer\Mapping\AttributeMetadataInterface;
35
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
36
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
37
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
38
use Symfony\Component\TypeInfo\Type;
39
use Symfony\Component\TypeInfo\Type\CollectionType;
40
use Symfony\Component\TypeInfo\Type\CompositeTypeInterface;
41
use Symfony\Component\TypeInfo\Type\ObjectType;
42
use Symfony\Component\TypeInfo\Type\WrappingTypeInterface;
43

44
/**
45
 * Converts between objects and array including HAL metadata.
46
 *
47
 * @author Kévin Dunglas <dunglas@gmail.com>
48
 */
49
final class ItemNormalizer extends AbstractItemNormalizer
50
{
51
    use CacheKeyTrait;
52
    use ClassInfoTrait;
53
    use ContextTrait;
54

55
    public const FORMAT = 'jsonhal';
56

57
    protected const HAL_CIRCULAR_REFERENCE_LIMIT_COUNTERS = 'hal_circular_reference_limit_counters';
58

59
    private array $componentsCache = [];
60
    private array $attributesMetadataCache = [];
61

62
    public function __construct(PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, IriConverterInterface $iriConverter, ResourceClassResolverInterface $resourceClassResolver, ?PropertyAccessorInterface $propertyAccessor = null, ?NameConverterInterface $nameConverter = null, ?ClassMetadataFactoryInterface $classMetadataFactory = null, array $defaultContext = [], ?ResourceMetadataCollectionFactoryInterface $resourceMetadataCollectionFactory = null, ?ResourceAccessCheckerInterface $resourceAccessChecker = null, ?TagCollectorInterface $tagCollector = null)
63
    {
64
        $defaultContext[AbstractNormalizer::CIRCULAR_REFERENCE_HANDLER] = function ($object): ?array {
1,561✔
65
            $iri = $this->iriConverter->getIriFromResource($object);
×
66
            if (null === $iri) {
×
67
                return null;
×
68
            }
69

70
            return ['_links' => ['self' => ['href' => $iri]]];
×
71
        };
1,561✔
72

73
        parent::__construct($propertyNameCollectionFactory, $propertyMetadataFactory, $iriConverter, $resourceClassResolver, $propertyAccessor, $nameConverter, $classMetadataFactory, $defaultContext, $resourceMetadataCollectionFactory, $resourceAccessChecker, $tagCollector);
1,561✔
74
    }
75

76
    /**
77
     * {@inheritdoc}
78
     */
79
    public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
80
    {
81
        return self::FORMAT === $format && parent::supportsNormalization($data, $format, $context);
75✔
82
    }
83

84
    public function getSupportedTypes($format): array
85
    {
86
        return self::FORMAT === $format ? parent::getSupportedTypes($format) : [];
1,421✔
87
    }
88

89
    /**
90
     * {@inheritdoc}
91
     */
92
    public function normalize(mixed $object, ?string $format = null, array $context = []): array|string|int|float|bool|\ArrayObject|null
93
    {
94
        $resourceClass = $this->getObjectClass($object);
72✔
95
        if ($this->getOutputClass($context)) {
72✔
96
            return parent::normalize($object, $format, $context);
4✔
97
        }
98

99
        $previousResourceClass = $context['resource_class'] ?? null;
72✔
100
        if ($this->resourceClassResolver->isResourceClass($resourceClass) && (null === $previousResourceClass || $this->resourceClassResolver->isResourceClass($previousResourceClass))) {
72✔
101
            $resourceClass = $this->resourceClassResolver->getResourceClass($object, $previousResourceClass);
68✔
102
        }
103

104
        $context = $this->initContext($resourceClass, $context);
72✔
105

106
        $iri = $context['iri'] ??= $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_PATH, $context['operation'] ?? null, $context);
72✔
107
        $context['object'] = $object;
72✔
108
        $context['format'] = $format;
72✔
109
        $context['api_normalize'] = true;
72✔
110

111
        if (!isset($context['cache_key'])) {
72✔
112
            $context['cache_key'] = $this->getCacheKey($format, $context);
72✔
113
        }
114

115
        $data = parent::normalize($object, $format, $context);
72✔
116

117
        if (!\is_array($data)) {
72✔
118
            return $data;
×
119
        }
120

121
        $metadata = [
72✔
122
            '_links' => [
72✔
123
                'self' => [
72✔
124
                    'href' => $iri,
72✔
125
                ],
72✔
126
            ],
72✔
127
        ];
72✔
128
        $components = $this->getComponents($object, $format, $context);
72✔
129
        $metadata = $this->populateRelation($metadata, $object, $format, $context, $components, 'links');
72✔
130
        $metadata = $this->populateRelation($metadata, $object, $format, $context, $components, 'embedded');
72✔
131

132
        return $metadata + $data;
72✔
133
    }
134

135
    /**
136
     * {@inheritdoc}
137
     */
138
    public function supportsDenormalization(mixed $data, string $type, ?string $format = null, array $context = []): bool
139
    {
140
        // prevent the use of lower priority normalizers (e.g. serializer.normalizer.object) for this format
UNCOV
141
        return self::FORMAT === $format;
×
142
    }
143

144
    /**
145
     * {@inheritdoc}
146
     *
147
     * @throws LogicException
148
     */
149
    public function denormalize(mixed $data, string $type, ?string $format = null, array $context = []): never
150
    {
UNCOV
151
        throw new LogicException(\sprintf('%s is a read-only format.', self::FORMAT));
×
152
    }
153

154
    /**
155
     * {@inheritdoc}
156
     */
157
    protected function getAttributes($object, $format = null, array $context = []): array
158
    {
159
        return $this->getComponents($object, $format, $context)['states'];
72✔
160
    }
161

162
    /**
163
     * Gets HAL components of the resource: states, links and embedded.
164
     */
165
    private function getComponents(object $object, ?string $format, array $context): array
166
    {
167
        $cacheKey = $this->getObjectClass($object).'-'.$context['cache_key'];
72✔
168

169
        if (isset($this->componentsCache[$cacheKey])) {
72✔
170
            return $this->componentsCache[$cacheKey];
72✔
171
        }
172

173
        $attributes = parent::getAttributes($object, $format, $context);
72✔
174
        $options = $this->getFactoryOptions($context);
72✔
175

176
        $components = [
72✔
177
            'states' => [],
72✔
178
            'links' => [],
72✔
179
            'embedded' => [],
72✔
180
        ];
72✔
181

182
        foreach ($attributes as $attribute) {
72✔
183
            $propertyMetadata = $this->propertyMetadataFactory->create($context['resource_class'], $attribute, $options);
72✔
184

185
            if (method_exists(PropertyInfoExtractor::class, 'getType')) {
72✔
186
                $type = $propertyMetadata->getNativeType();
72✔
187
                $types = $type instanceof CompositeTypeInterface ? $type->getTypes() : (null === $type ? [] : [$type]);
72✔
188
                /** @var class-string|null $className */
189
                $className = null;
72✔
190
            } else {
191
                $types = $propertyMetadata->getBuiltinTypes() ?? [];
×
192
            }
193

194
            // prevent declaring $attribute as attribute if it's already declared as relationship
195
            $isRelationship = false;
72✔
196
            $typeIsResourceClass = function (Type $type) use (&$className): bool {
72✔
197
                return $type instanceof ObjectType && $this->resourceClassResolver->isResourceClass($className = $type->getClassName());
68✔
198
            };
72✔
199

200
            foreach ($types as $type) {
72✔
201
                $isOne = $isMany = false;
68✔
202

203
                /** @var Type|LegacyType|null $valueType */
204
                $valueType = null;
68✔
205

206
                if ($type instanceof LegacyType) {
68✔
UNCOV
207
                    if ($type->isCollection()) {
×
UNCOV
208
                        $valueType = $type->getCollectionValueTypes()[0] ?? null;
×
UNCOV
209
                        $isMany = null !== $valueType && ($className = $valueType->getClassName()) && $this->resourceClassResolver->isResourceClass($className);
×
210
                    } else {
211
                        $className = $type->getClassName();
×
212
                        $isOne = $className && $this->resourceClassResolver->isResourceClass($className);
×
213
                    }
214
                } elseif ($type instanceof Type) {
68✔
215
                    $typeIsCollection = function (Type $type) use (&$typeIsCollection, &$valueType): bool {
68✔
216
                        return match (true) {
217
                            $type instanceof CollectionType => null !== $valueType = $type->getCollectionValueType(),
68✔
218
                            $type instanceof WrappingTypeInterface => $type->wrappedTypeIsSatisfiedBy($typeIsCollection),
68✔
219
                            $type instanceof CompositeTypeInterface => $type->composedTypesAreSatisfiedBy($typeIsCollection),
68✔
220
                            default => false,
68✔
221
                        };
222
                    };
68✔
223

224
                    if ($type->isSatisfiedBy($typeIsCollection)) {
68✔
225
                        $isMany = $valueType->isSatisfiedBy($typeIsResourceClass);
36✔
226
                    } else {
227
                        $isOne = $type->isSatisfiedBy($typeIsResourceClass);
68✔
228
                    }
229
                }
230

231
                if (!$isOne && !$isMany) {
68✔
232
                    // don't declare it as an attribute too quick: maybe the next type is a valid resource
233
                    continue;
68✔
234
                }
235

236
                $relation = ['name' => $attribute, 'cardinality' => $isOne ? 'one' : 'many', 'iri' => null, 'operation' => null];
63✔
237

238
                // if we specify the uriTemplate, generates its value for link definition
239
                // @see ApiPlatform\Serializer\AbstractItemNormalizer:getAttributeValue logic for intentional duplicate content
240
                if (($className ?? false) && $uriTemplate = $propertyMetadata->getUriTemplate()) {
63✔
241
                    $childContext = $this->createChildContext($context, $attribute, $format);
2✔
242
                    unset($childContext['iri'], $childContext['uri_variables'], $childContext['resource_class'], $childContext['operation'], $childContext['operation_name']);
2✔
243

244
                    $operation = $this->resourceMetadataCollectionFactory->create($className)->getOperation(
2✔
245
                        operationName: $uriTemplate,
2✔
246
                        httpOperation: true
2✔
247
                    );
2✔
248

249
                    $relation['iri'] = $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_PATH, $operation, $childContext);
2✔
250
                    $relation['operation'] = $operation;
2✔
251
                    $cacheKey = null;
2✔
252
                }
253

254
                if ($propertyMetadata->isReadableLink()) {
63✔
255
                    $components['embedded'][] = $relation;
17✔
256
                }
257

258
                $components['links'][] = $relation;
63✔
259
                $isRelationship = true;
63✔
260
            }
261

262
            // if all types are not relationships, declare it as an attribute
263
            if (!$isRelationship) {
72✔
264
                $components['states'][] = $attribute;
72✔
265
            }
266
        }
267

268
        if ($cacheKey && false !== $context['cache_key']) {
72✔
269
            $this->componentsCache[$cacheKey] = $components;
72✔
270
        }
271

272
        return $components;
72✔
273
    }
274

275
    /**
276
     * Populates _links and _embedded keys.
277
     */
278
    private function populateRelation(array $data, object $object, ?string $format, array $context, array $components, string $type): array
279
    {
280
        $class = $this->getObjectClass($object);
72✔
281

282
        if ($this->isHalCircularReference($object, $context)) {
72✔
UNCOV
283
            return $this->handleHalCircularReference($object, $format, $context);
×
284
        }
285

286
        $attributesMetadata = \array_key_exists($class, $this->attributesMetadataCache) ?
72✔
287
            $this->attributesMetadataCache[$class] :
72✔
288
            $this->attributesMetadataCache[$class] = $this->classMetadataFactory ? $this->classMetadataFactory->getMetadataFor($class)->getAttributesMetadata() : null;
72✔
289

290
        $key = '_'.$type;
72✔
291
        foreach ($components[$type] as $relation) {
72✔
292
            if (null !== $attributesMetadata && $this->isMaxDepthReached($attributesMetadata, $class, $relation['name'], $context)) {
63✔
293
                continue;
6✔
294
            }
295

296
            $relationName = $relation['name'];
63✔
297
            if ($this->nameConverter) {
63✔
298
                $relationName = $this->nameConverter->normalize($relationName, $class, $format, $context);
63✔
299
            }
300

301
            // if we specify the uriTemplate, then the link takes the uriTemplate defined.
302
            if ('links' === $type && $iri = $relation['iri']) {
63✔
303
                $data[$key][$relationName]['href'] = $iri;
2✔
304
                continue;
2✔
305
            }
306

307
            $childContext = $this->createChildContext($context, $relationName, $format);
63✔
308
            unset($childContext['iri'], $childContext['uri_variables'], $childContext['operation'], $childContext['operation_name']);
63✔
309

310
            if ($operation = $relation['operation']) {
63✔
311
                $childContext['operation'] = $operation;
2✔
312
                $childContext['operation_name'] = $operation->getName();
2✔
313
            }
314

315
            $attributeValue = $this->getAttributeValue($object, $relation['name'], $format, $childContext);
63✔
316

317
            if (empty($attributeValue)) {
63✔
318
                continue;
40✔
319
            }
320

321
            if ('one' === $relation['cardinality']) {
40✔
322
                if ('links' === $type) {
33✔
323
                    $data[$key][$relationName]['href'] = $this->getRelationIri($attributeValue);
31✔
324
                    continue;
31✔
325
                }
326

327
                $data[$key][$relationName] = $attributeValue;
15✔
328
                continue;
15✔
329
            }
330

331
            // many
332
            $data[$key][$relationName] = [];
17✔
333
            foreach ($attributeValue as $rel) {
17✔
334
                if ('links' === $type) {
17✔
335
                    $rel = ['href' => $this->getRelationIri($rel)];
15✔
336
                }
337

338
                $data[$key][$relationName][] = $rel;
17✔
339
            }
340
        }
341

342
        return $data;
72✔
343
    }
344

345
    /**
346
     * Gets the IRI of the given relation.
347
     *
348
     * @throws UnexpectedValueException
349
     */
350
    private function getRelationIri(mixed $rel): string
351
    {
352
        if (!(\is_array($rel) || \is_string($rel))) {
38✔
UNCOV
353
            throw new UnexpectedValueException('Expected relation to be an IRI or array');
×
354
        }
355

356
        return \is_string($rel) ? $rel : $rel['_links']['self']['href'];
38✔
357
    }
358

359
    /**
360
     * Is the max depth reached for the given attribute?
361
     *
362
     * @param AttributeMetadataInterface[] $attributesMetadata
363
     */
364
    private function isMaxDepthReached(array $attributesMetadata, string $class, string $attribute, array &$context): bool
365
    {
366
        if (
367
            !($context[self::ENABLE_MAX_DEPTH] ?? false)
63✔
368
            || !isset($attributesMetadata[$attribute])
63✔
369
            || null === $maxDepth = $attributesMetadata[$attribute]->getMaxDepth()
63✔
370
        ) {
371
            return false;
57✔
372
        }
373

374
        $key = \sprintf(self::DEPTH_KEY_PATTERN, $class, $attribute);
6✔
375
        if (!isset($context[$key])) {
6✔
376
            $context[$key] = 1;
6✔
377

378
            return false;
6✔
379
        }
380

381
        if ($context[$key] === $maxDepth) {
6✔
382
            return true;
6✔
383
        }
384

UNCOV
385
        ++$context[$key];
×
386

UNCOV
387
        return false;
×
388
    }
389

390
    /**
391
     * Detects if the configured circular reference limit is reached.
392
     *
393
     * @throws CircularReferenceException
394
     */
395
    protected function isHalCircularReference(object $object, array &$context): bool
396
    {
397
        $objectHash = spl_object_hash($object);
72✔
398

399
        $circularReferenceLimit = $context[AbstractNormalizer::CIRCULAR_REFERENCE_LIMIT] ?? $this->defaultContext[AbstractNormalizer::CIRCULAR_REFERENCE_LIMIT];
72✔
400
        if (isset($context[self::HAL_CIRCULAR_REFERENCE_LIMIT_COUNTERS][$objectHash])) {
72✔
UNCOV
401
            if ($context[self::HAL_CIRCULAR_REFERENCE_LIMIT_COUNTERS][$objectHash] >= $circularReferenceLimit) {
×
UNCOV
402
                unset($context[self::HAL_CIRCULAR_REFERENCE_LIMIT_COUNTERS][$objectHash]);
×
403

UNCOV
404
                return true;
×
405
            }
406

UNCOV
407
            ++$context[self::HAL_CIRCULAR_REFERENCE_LIMIT_COUNTERS][$objectHash];
×
408
        } else {
409
            $context[self::HAL_CIRCULAR_REFERENCE_LIMIT_COUNTERS][$objectHash] = 1;
72✔
410
        }
411

412
        return false;
72✔
413
    }
414

415
    /**
416
     * Handles a circular reference.
417
     *
418
     * If a circular reference handler is set, it will be called. Otherwise, a
419
     * {@class CircularReferenceException} will be thrown.
420
     *
421
     * @final
422
     *
423
     * @throws CircularReferenceException
424
     */
425
    protected function handleHalCircularReference(object $object, ?string $format = null, array $context = []): mixed
426
    {
UNCOV
427
        $circularReferenceHandler = $context[AbstractNormalizer::CIRCULAR_REFERENCE_HANDLER] ?? $this->defaultContext[AbstractNormalizer::CIRCULAR_REFERENCE_HANDLER];
×
UNCOV
428
        if ($circularReferenceHandler) {
×
UNCOV
429
            return $circularReferenceHandler($object, $format, $context);
×
430
        }
431

432
        throw new CircularReferenceException(\sprintf('A circular reference has been detected when serializing the object of class "%s" (configured limit: %d).', get_debug_type($object), $context[AbstractNormalizer::CIRCULAR_REFERENCE_LIMIT] ?? $this->defaultContext[AbstractNormalizer::CIRCULAR_REFERENCE_LIMIT]));
×
433
    }
434
}
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