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

api-platform / core / 14246153067

03 Apr 2025 02:56PM UTC coverage: 7.286% (-0.002%) from 7.288%
14246153067

push

github

web-flow
Merge commit from fork

12 of 160 new or added lines in 7 files covered. (7.5%)

2343 existing lines in 152 files now uncovered.

12450 of 170870 relevant lines covered (7.29%)

12.06 hits per line

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

88.44
/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\Serializer\Exception\CircularReferenceException;
30
use Symfony\Component\Serializer\Exception\LogicException;
31
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
32
use Symfony\Component\Serializer\Mapping\AttributeMetadataInterface;
33
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
34
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
35
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
36

37
/**
38
 * Converts between objects and array including HAL metadata.
39
 *
40
 * @author Kévin Dunglas <dunglas@gmail.com>
41
 */
42
final class ItemNormalizer extends AbstractItemNormalizer
43
{
44
    use CacheKeyTrait;
45
    use ClassInfoTrait;
46
    use ContextTrait;
47

48
    public const FORMAT = 'jsonhal';
49

50
    protected const HAL_CIRCULAR_REFERENCE_LIMIT_COUNTERS = 'hal_circular_reference_limit_counters';
51

52
    private array $componentsCache = [];
53
    private array $attributesMetadataCache = [];
54

55
    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)
56
    {
57
        $defaultContext[AbstractNormalizer::CIRCULAR_REFERENCE_HANDLER] = function ($object): ?array {
1,126✔
58
            $iri = $this->iriConverter->getIriFromResource($object);
×
59
            if (null === $iri) {
×
60
                return null;
×
61
            }
62

63
            return ['_links' => ['self' => ['href' => $iri]]];
×
64
        };
1,126✔
65

66
        parent::__construct($propertyNameCollectionFactory, $propertyMetadataFactory, $iriConverter, $resourceClassResolver, $propertyAccessor, $nameConverter, $classMetadataFactory, $defaultContext, $resourceMetadataCollectionFactory, $resourceAccessChecker, $tagCollector);
1,126✔
67
    }
68

69
    /**
70
     * {@inheritdoc}
71
     */
72
    public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
73
    {
74
        return self::FORMAT === $format && parent::supportsNormalization($data, $format, $context);
83✔
75
    }
76

77
    public function getSupportedTypes($format): array
78
    {
79
        return self::FORMAT === $format ? parent::getSupportedTypes($format) : [];
987✔
80
    }
81

82
    /**
83
     * {@inheritdoc}
84
     */
85
    public function normalize(mixed $object, ?string $format = null, array $context = []): array|string|int|float|bool|\ArrayObject|null
86
    {
87
        $resourceClass = $this->getObjectClass($object);
88✔
88
        if ($this->getOutputClass($context)) {
88✔
89
            return parent::normalize($object, $format, $context);
5✔
90
        }
91

92
        $previousResourceClass = $context['resource_class'] ?? null;
88✔
93
        if ($this->resourceClassResolver->isResourceClass($resourceClass) && (null === $previousResourceClass || $this->resourceClassResolver->isResourceClass($previousResourceClass))) {
88✔
94
            $resourceClass = $this->resourceClassResolver->getResourceClass($object, $previousResourceClass);
83✔
95
        }
96

97
        $context = $this->initContext($resourceClass, $context);
88✔
98

99
        $iri = $context['iri'] ??= $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_PATH, $context['operation'] ?? null, $context);
88✔
100
        $context['object'] = $object;
88✔
101
        $context['format'] = $format;
88✔
102
        $context['api_normalize'] = true;
88✔
103

104
        if (!isset($context['cache_key'])) {
88✔
105
            $context['cache_key'] = $this->getCacheKey($format, $context);
88✔
106
        }
107

108
        $data = parent::normalize($object, $format, $context);
88✔
109

110
        if (!\is_array($data)) {
88✔
111
            return $data;
×
112
        }
113

114
        $metadata = [
88✔
115
            '_links' => [
88✔
116
                'self' => [
88✔
117
                    'href' => $iri,
88✔
118
                ],
88✔
119
            ],
88✔
120
        ];
88✔
121
        $components = $this->getComponents($object, $format, $context);
88✔
122
        $metadata = $this->populateRelation($metadata, $object, $format, $context, $components, 'links');
88✔
123
        $metadata = $this->populateRelation($metadata, $object, $format, $context, $components, 'embedded');
85✔
124

125
        return $metadata + $data;
85✔
126
    }
127

128
    /**
129
     * {@inheritdoc}
130
     */
131
    public function supportsDenormalization(mixed $data, string $type, ?string $format = null, array $context = []): bool
132
    {
133
        // prevent the use of lower priority normalizers (e.g. serializer.normalizer.object) for this format
134
        return self::FORMAT === $format;
3✔
135
    }
136

137
    /**
138
     * {@inheritdoc}
139
     *
140
     * @throws LogicException
141
     */
142
    public function denormalize(mixed $data, string $type, ?string $format = null, array $context = []): never
143
    {
144
        throw new LogicException(\sprintf('%s is a read-only format.', self::FORMAT));
3✔
145
    }
146

147
    /**
148
     * {@inheritdoc}
149
     */
150
    protected function getAttributes($object, $format = null, array $context = []): array
151
    {
152
        return $this->getComponents($object, $format, $context)['states'];
88✔
153
    }
154

155
    /**
156
     * Gets HAL components of the resource: states, links and embedded.
157
     */
158
    private function getComponents(object $object, ?string $format, array $context): array
159
    {
160
        $cacheKey = $this->getObjectClass($object).'-'.$context['cache_key'];
88✔
161

162
        if (isset($this->componentsCache[$cacheKey])) {
88✔
163
            return $this->componentsCache[$cacheKey];
85✔
164
        }
165

166
        $attributes = parent::getAttributes($object, $format, $context);
88✔
167
        $options = $this->getFactoryOptions($context);
88✔
168

169
        $components = [
88✔
170
            'states' => [],
88✔
171
            'links' => [],
88✔
172
            'embedded' => [],
88✔
173
        ];
88✔
174

175
        foreach ($attributes as $attribute) {
88✔
176
            $propertyMetadata = $this->propertyMetadataFactory->create($context['resource_class'], $attribute, $options);
85✔
177

178
            $types = $propertyMetadata->getBuiltinTypes() ?? [];
85✔
179

180
            // prevent declaring $attribute as attribute if it's already declared as relationship
181
            $isRelationship = false;
85✔
182

183
            foreach ($types as $type) {
85✔
184
                $isOne = $isMany = false;
83✔
185

186
                if (null !== $type) {
83✔
187
                    if ($type->isCollection()) {
83✔
188
                        $valueType = $type->getCollectionValueTypes()[0] ?? null;
23✔
189
                        $isMany = null !== $valueType && ($className = $valueType->getClassName()) && $this->resourceClassResolver->isResourceClass($className);
23✔
190
                    } else {
191
                        $className = $type->getClassName();
83✔
192
                        $isOne = $className && $this->resourceClassResolver->isResourceClass($className);
83✔
193
                    }
194
                }
195

196
                if (!$isOne && !$isMany) {
83✔
197
                    // don't declare it as an attribute too quick: maybe the next type is a valid resource
198
                    continue;
83✔
199
                }
200

201
                $relation = ['name' => $attribute, 'cardinality' => $isOne ? 'one' : 'many', 'iri' => null, 'operation' => null];
42✔
202

203
                // if we specify the uriTemplate, generates its value for link definition
204
                // @see ApiPlatform\Serializer\AbstractItemNormalizer:getAttributeValue logic for intentional duplicate content
205
                if (($className ?? false) && $uriTemplate = $propertyMetadata->getUriTemplate()) {
42✔
UNCOV
206
                    $childContext = $this->createChildContext($context, $attribute, $format);
1✔
UNCOV
207
                    unset($childContext['iri'], $childContext['uri_variables'], $childContext['resource_class'], $childContext['operation'], $childContext['operation_name']);
1✔
208

UNCOV
209
                    $operation = $this->resourceMetadataCollectionFactory->create($className)->getOperation(
1✔
UNCOV
210
                        operationName: $uriTemplate,
1✔
UNCOV
211
                        httpOperation: true
1✔
UNCOV
212
                    );
1✔
213

UNCOV
214
                    $relation['iri'] = $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_PATH, $operation, $childContext);
1✔
UNCOV
215
                    $relation['operation'] = $operation;
1✔
UNCOV
216
                    $cacheKey = null;
1✔
217
                }
218

219
                if ($propertyMetadata->isReadableLink()) {
42✔
220
                    $components['embedded'][] = $relation;
14✔
221
                }
222

223
                $components['links'][] = $relation;
42✔
224
                $isRelationship = true;
42✔
225
            }
226

227
            // if all types are not relationships, declare it as an attribute
228
            if (!$isRelationship) {
85✔
229
                $components['states'][] = $attribute;
85✔
230
            }
231
        }
232

233
        if ($cacheKey && false !== $context['cache_key']) {
88✔
234
            $this->componentsCache[$cacheKey] = $components;
85✔
235
        }
236

237
        return $components;
88✔
238
    }
239

240
    /**
241
     * Populates _links and _embedded keys.
242
     */
243
    private function populateRelation(array $data, object $object, ?string $format, array $context, array $components, string $type): array
244
    {
245
        $class = $this->getObjectClass($object);
88✔
246

247
        if ($this->isHalCircularReference($object, $context)) {
88✔
248
            return $this->handleHalCircularReference($object, $format, $context);
×
249
        }
250

251
        $attributesMetadata = \array_key_exists($class, $this->attributesMetadataCache) ?
88✔
252
            $this->attributesMetadataCache[$class] :
85✔
253
            $this->attributesMetadataCache[$class] = $this->classMetadataFactory ? $this->classMetadataFactory->getMetadataFor($class)->getAttributesMetadata() : null;
88✔
254

255
        $key = '_'.$type;
88✔
256
        foreach ($components[$type] as $relation) {
88✔
257
            if (null !== $attributesMetadata && $this->isMaxDepthReached($attributesMetadata, $class, $relation['name'], $context)) {
42✔
258
                continue;
6✔
259
            }
260

261
            $relationName = $relation['name'];
42✔
262
            if ($this->nameConverter) {
42✔
263
                $relationName = $this->nameConverter->normalize($relationName, $class, $format, $context);
39✔
264
            }
265

266
            // if we specify the uriTemplate, then the link takes the uriTemplate defined.
267
            if ('links' === $type && $iri = $relation['iri']) {
42✔
UNCOV
268
                $data[$key][$relationName]['href'] = $iri;
1✔
UNCOV
269
                continue;
1✔
270
            }
271

272
            $childContext = $this->createChildContext($context, $relationName, $format);
42✔
273
            unset($childContext['iri'], $childContext['uri_variables'], $childContext['operation'], $childContext['operation_name']);
42✔
274

275
            if ($operation = $relation['operation']) {
42✔
UNCOV
276
                $childContext['operation'] = $operation;
1✔
UNCOV
277
                $childContext['operation_name'] = $operation->getName();
1✔
278
            }
279

280
            $attributeValue = $this->getAttributeValue($object, $relation['name'], $format, $childContext);
42✔
281

282
            if (empty($attributeValue)) {
39✔
283
                continue;
22✔
284
            }
285

286
            if ('one' === $relation['cardinality']) {
28✔
287
                if ('links' === $type) {
25✔
288
                    $data[$key][$relationName]['href'] = $this->getRelationIri($attributeValue);
24✔
289
                    continue;
24✔
290
                }
291

292
                $data[$key][$relationName] = $attributeValue;
10✔
293
                continue;
10✔
294
            }
295

296
            // many
UNCOV
297
            $data[$key][$relationName] = [];
8✔
UNCOV
298
            foreach ($attributeValue as $rel) {
8✔
UNCOV
299
                if ('links' === $type) {
8✔
UNCOV
300
                    $rel = ['href' => $this->getRelationIri($rel)];
7✔
301
                }
302

UNCOV
303
                $data[$key][$relationName][] = $rel;
8✔
304
            }
305
        }
306

307
        return $data;
85✔
308
    }
309

310
    /**
311
     * Gets the IRI of the given relation.
312
     *
313
     * @throws UnexpectedValueException
314
     */
315
    private function getRelationIri(mixed $rel): string
316
    {
317
        if (!(\is_array($rel) || \is_string($rel))) {
27✔
318
            throw new UnexpectedValueException('Expected relation to be an IRI or array');
×
319
        }
320

321
        return \is_string($rel) ? $rel : $rel['_links']['self']['href'];
27✔
322
    }
323

324
    /**
325
     * Is the max depth reached for the given attribute?
326
     *
327
     * @param AttributeMetadataInterface[] $attributesMetadata
328
     */
329
    private function isMaxDepthReached(array $attributesMetadata, string $class, string $attribute, array &$context): bool
330
    {
331
        if (
332
            !($context[self::ENABLE_MAX_DEPTH] ?? false)
36✔
333
            || !isset($attributesMetadata[$attribute])
36✔
334
            || null === $maxDepth = $attributesMetadata[$attribute]->getMaxDepth()
36✔
335
        ) {
336
            return false;
33✔
337
        }
338

339
        $key = \sprintf(self::DEPTH_KEY_PATTERN, $class, $attribute);
6✔
340
        if (!isset($context[$key])) {
6✔
341
            $context[$key] = 1;
6✔
342

343
            return false;
6✔
344
        }
345

346
        if ($context[$key] === $maxDepth) {
6✔
347
            return true;
6✔
348
        }
349

350
        ++$context[$key];
×
351

352
        return false;
×
353
    }
354

355
    /**
356
     * Detects if the configured circular reference limit is reached.
357
     *
358
     * @throws CircularReferenceException
359
     */
360
    protected function isHalCircularReference(object $object, array &$context): bool
361
    {
362
        $objectHash = spl_object_hash($object);
88✔
363

364
        $circularReferenceLimit = $context[AbstractNormalizer::CIRCULAR_REFERENCE_LIMIT] ?? $this->defaultContext[AbstractNormalizer::CIRCULAR_REFERENCE_LIMIT];
88✔
365
        if (isset($context[self::HAL_CIRCULAR_REFERENCE_LIMIT_COUNTERS][$objectHash])) {
88✔
366
            if ($context[self::HAL_CIRCULAR_REFERENCE_LIMIT_COUNTERS][$objectHash] >= $circularReferenceLimit) {
×
367
                unset($context[self::HAL_CIRCULAR_REFERENCE_LIMIT_COUNTERS][$objectHash]);
×
368

369
                return true;
×
370
            }
371

372
            ++$context[self::HAL_CIRCULAR_REFERENCE_LIMIT_COUNTERS][$objectHash];
×
373
        } else {
374
            $context[self::HAL_CIRCULAR_REFERENCE_LIMIT_COUNTERS][$objectHash] = 1;
88✔
375
        }
376

377
        return false;
88✔
378
    }
379

380
    /**
381
     * Handles a circular reference.
382
     *
383
     * If a circular reference handler is set, it will be called. Otherwise, a
384
     * {@class CircularReferenceException} will be thrown.
385
     *
386
     * @final
387
     *
388
     * @throws CircularReferenceException
389
     */
390
    protected function handleHalCircularReference(object $object, ?string $format = null, array $context = []): mixed
391
    {
392
        $circularReferenceHandler = $context[AbstractNormalizer::CIRCULAR_REFERENCE_HANDLER] ?? $this->defaultContext[AbstractNormalizer::CIRCULAR_REFERENCE_HANDLER];
×
393
        if ($circularReferenceHandler) {
×
394
            return $circularReferenceHandler($object, $format, $context);
×
395
        }
396

397
        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]));
×
398
    }
399
}
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