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

api-platform / core / 18060089452

27 Sep 2025 12:57PM UTC coverage: 0.0% (-21.8%) from 21.793%
18060089452

Pull #7397

github

web-flow
Merge 479f46b8d into abe0438be
Pull Request #7397: fix(jsonschema/jsonld): make `@id` and `@type` properties required only in the JSON-LD schema for output

0 of 15 new or added lines in 1 file covered. (0.0%)

11967 existing lines in 393 files now uncovered.

0 of 53914 relevant lines covered (0.0%)

0.0 hits per line

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

0.0
/src/JsonApi/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\JsonApi\Serializer;
15

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

45
/**
46
 * Converts between objects and array.
47
 *
48
 * @author Kévin Dunglas <dunglas@gmail.com>
49
 * @author Amrouche Hamza <hamza.simperfit@gmail.com>
50
 * @author Baptiste Meyer <baptiste.meyer@gmail.com>
51
 */
52
final class ItemNormalizer extends AbstractItemNormalizer
53
{
54
    use CacheKeyTrait;
55
    use ClassInfoTrait;
56
    use ContextTrait;
57

58
    public const FORMAT = 'jsonapi';
59

60
    private array $componentsCache = [];
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, protected ?TagCollectorInterface $tagCollector = null)
63
    {
UNCOV
64
        parent::__construct($propertyNameCollectionFactory, $propertyMetadataFactory, $iriConverter, $resourceClassResolver, $propertyAccessor, $nameConverter, $classMetadataFactory, $defaultContext, $resourceMetadataCollectionFactory, $resourceAccessChecker, $tagCollector);
×
65
    }
66

67
    /**
68
     * {@inheritdoc}
69
     */
70
    public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
71
    {
UNCOV
72
        return self::FORMAT === $format && parent::supportsNormalization($data, $format, $context) && !($data instanceof \Exception || $data instanceof FlattenException);
×
73
    }
74

75
    /**
76
     * @param string|null $format
77
     */
78
    public function getSupportedTypes($format): array
79
    {
UNCOV
80
        return self::FORMAT === $format ? parent::getSupportedTypes($format) : [];
×
81
    }
82

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

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

UNCOV
98
        if (($operation = $context['operation'] ?? null) && method_exists($operation, 'getItemUriTemplate')) {
×
99
            $context['item_uri_template'] = $operation->getItemUriTemplate();
×
100
        }
101

UNCOV
102
        $context = $this->initContext($resourceClass, $context);
×
103

UNCOV
104
        $iri = $context['iri'] ??= $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_PATH, $context['operation'] ?? null, $context);
×
UNCOV
105
        $context['object'] = $object;
×
UNCOV
106
        $context['format'] = $format;
×
UNCOV
107
        $context['api_normalize'] = true;
×
108

UNCOV
109
        if (!isset($context['cache_key'])) {
×
UNCOV
110
            $context['cache_key'] = $this->getCacheKey($format, $context);
×
111
        }
112

UNCOV
113
        $data = parent::normalize($object, $format, $context);
×
UNCOV
114
        if (!\is_array($data)) {
×
115
            return $data;
×
116
        }
117

118
        // Get and populate relations
UNCOV
119
        ['relationships' => $allRelationshipsData, 'links' => $links] = $this->getComponents($object, $format, $context);
×
UNCOV
120
        $populatedRelationContext = $context;
×
UNCOV
121
        $relationshipsData = $this->getPopulatedRelations($object, $format, $populatedRelationContext, $allRelationshipsData);
×
122

123
        // Do not include primary resources
UNCOV
124
        $context['api_included_resources'] = [$context['iri']];
×
125

UNCOV
126
        $includedResourcesData = $this->getRelatedResources($object, $format, $context, $allRelationshipsData);
×
127

UNCOV
128
        $resourceData = [
×
UNCOV
129
            'id' => $context['iri'],
×
UNCOV
130
            'type' => $this->getResourceShortName($resourceClass),
×
UNCOV
131
        ];
×
132

UNCOV
133
        if ($data) {
×
UNCOV
134
            $resourceData['attributes'] = $data;
×
135
        }
136

UNCOV
137
        if ($relationshipsData) {
×
UNCOV
138
            $resourceData['relationships'] = $relationshipsData;
×
139
        }
140

UNCOV
141
        $document = [];
×
142

UNCOV
143
        if ($links) {
×
144
            $document['links'] = $links;
×
145
        }
146

UNCOV
147
        $document['data'] = $resourceData;
×
148

UNCOV
149
        if ($includedResourcesData) {
×
150
            $document['included'] = $includedResourcesData;
×
151
        }
152

UNCOV
153
        return $document;
×
154
    }
155

156
    /**
157
     * {@inheritdoc}
158
     */
159
    public function supportsDenormalization(mixed $data, string $type, ?string $format = null, array $context = []): bool
160
    {
161
        return self::FORMAT === $format && parent::supportsDenormalization($data, $type, $format, $context);
×
162
    }
163

164
    /**
165
     * {@inheritdoc}
166
     *
167
     * @throws NotNormalizableValueException
168
     */
169
    public function denormalize(mixed $data, string $class, ?string $format = null, array $context = []): mixed
170
    {
171
        // Avoid issues with proxies if we populated the object
172
        if (!isset($context[self::OBJECT_TO_POPULATE]) && isset($data['data']['id'])) {
×
173
            if (true !== ($context['api_allow_update'] ?? true)) {
×
174
                throw new NotNormalizableValueException('Update is not allowed for this operation.');
×
175
            }
176

177
            $context[self::OBJECT_TO_POPULATE] = $this->iriConverter->getResourceFromIri(
×
178
                $data['data']['id'],
×
179
                $context + ['fetch_data' => false]
×
180
            );
×
181
        }
182

183
        // Merge attributes and relationships, into format expected by the parent normalizer
184
        $dataToDenormalize = array_merge(
×
185
            $data['data']['attributes'] ?? [],
×
186
            $data['data']['relationships'] ?? []
×
187
        );
×
188

189
        return parent::denormalize(
×
190
            $dataToDenormalize,
×
191
            $class,
×
192
            $format,
×
193
            $context
×
194
        );
×
195
    }
196

197
    /**
198
     * {@inheritdoc}
199
     */
200
    protected function getAttributes(object $object, ?string $format = null, array $context = []): array
201
    {
UNCOV
202
        return $this->getComponents($object, $format, $context)['attributes'];
×
203
    }
204

205
    /**
206
     * {@inheritdoc}
207
     */
208
    protected function setAttributeValue(object $object, string $attribute, mixed $value, ?string $format = null, array $context = []): void
209
    {
210
        parent::setAttributeValue($object, $attribute, \is_array($value) && \array_key_exists('data', $value) ? $value['data'] : $value, $format, $context);
×
211
    }
212

213
    /**
214
     * {@inheritdoc}
215
     *
216
     * @see http://jsonapi.org/format/#document-resource-object-linkage
217
     *
218
     * @throws RuntimeException
219
     * @throws UnexpectedValueException
220
     */
221
    protected function denormalizeRelation(string $attributeName, ApiProperty $propertyMetadata, string $className, mixed $value, ?string $format, array $context): ?object
222
    {
223
        if (!\is_array($value) || !isset($value['id'], $value['type'])) {
×
224
            throw new UnexpectedValueException('Only resource linkage supported currently, see: http://jsonapi.org/format/#document-resource-object-linkage.');
×
225
        }
226

227
        try {
228
            return $this->iriConverter->getResourceFromIri($value['id'], $context + ['fetch_data' => true]);
×
229
        } catch (ItemNotFoundException $e) {
×
230
            if (!isset($context['not_normalizable_value_exceptions'])) {
×
231
                throw new RuntimeException($e->getMessage(), $e->getCode(), $e);
×
232
            }
233
            $context['not_normalizable_value_exceptions'][] = NotNormalizableValueException::createForUnexpectedDataType(
×
234
                $e->getMessage(),
×
235
                $value,
×
236
                [$className],
×
237
                $context['deserialization_path'] ?? null,
×
238
                true,
×
239
                $e->getCode(),
×
240
                $e
×
241
            );
×
242

243
            return null;
×
244
        }
245
    }
246

247
    /**
248
     * {@inheritdoc}
249
     *
250
     * @see http://jsonapi.org/format/#document-resource-object-linkage
251
     */
252
    protected function normalizeRelation(ApiProperty $propertyMetadata, ?object $relatedObject, string $resourceClass, ?string $format, array $context): \ArrayObject|array|string|null
253
    {
254
        if (null !== $relatedObject) {
×
255
            $iri = $this->iriConverter->getIriFromResource($relatedObject);
×
256
            $context['iri'] = $iri;
×
257

258
            if (!$this->tagCollector && isset($context['resources'])) {
×
259
                $context['resources'][$iri] = $iri;
×
260
            }
261
        }
262

263
        if (null === $relatedObject || isset($context['api_included'])) {
×
264
            if (!$this->serializer instanceof NormalizerInterface) {
×
265
                throw new LogicException(\sprintf('The injected serializer must be an instance of "%s".', NormalizerInterface::class));
×
266
            }
267

268
            $normalizedRelatedObject = $this->serializer->normalize($relatedObject, $format, $context);
×
269
            if (!\is_string($normalizedRelatedObject) && !\is_array($normalizedRelatedObject) && !$normalizedRelatedObject instanceof \ArrayObject && null !== $normalizedRelatedObject) {
×
270
                throw new UnexpectedValueException('Expected normalized relation to be an IRI, array, \ArrayObject or null');
×
271
            }
272

273
            return $normalizedRelatedObject;
×
274
        }
275

276
        $context['data'] = [
×
277
            'data' => [
×
278
                'type' => $this->getResourceShortName($resourceClass),
×
279
                'id' => $iri,
×
280
            ],
×
281
        ];
×
282

283
        $context['iri'] = $iri;
×
284
        $context['object'] = $relatedObject;
×
285
        unset($context['property_metadata']);
×
286
        unset($context['api_attribute']);
×
287

288
        if ($this->tagCollector) {
×
289
            $this->tagCollector->collect($context);
×
290
        }
291

292
        return $context['data'];
×
293
    }
294

295
    /**
296
     * {@inheritdoc}
297
     */
298
    protected function isAllowedAttribute(object|string $classOrObject, string $attribute, ?string $format = null, array $context = []): bool
299
    {
UNCOV
300
        return preg_match('/^\\w[-\\w_]*$/', $attribute) && parent::isAllowedAttribute($classOrObject, $attribute, $format, $context);
×
301
    }
302

303
    /**
304
     * Gets JSON API components of the resource: attributes, relationships, meta and links.
305
     */
306
    private function getComponents(object $object, ?string $format, array $context): array
307
    {
UNCOV
308
        $cacheKey = $this->getObjectClass($object).'-'.$context['cache_key'];
×
309

UNCOV
310
        if (isset($this->componentsCache[$cacheKey])) {
×
UNCOV
311
            return $this->componentsCache[$cacheKey];
×
312
        }
313

UNCOV
314
        $attributes = parent::getAttributes($object, $format, $context);
×
315

UNCOV
316
        $options = $this->getFactoryOptions($context);
×
317

UNCOV
318
        $components = [
×
UNCOV
319
            'links' => [],
×
UNCOV
320
            'relationships' => [],
×
UNCOV
321
            'attributes' => [],
×
UNCOV
322
            'meta' => [],
×
UNCOV
323
        ];
×
324

UNCOV
325
        foreach ($attributes as $attribute) {
×
UNCOV
326
            $propertyMetadata = $this
×
UNCOV
327
                ->propertyMetadataFactory
×
UNCOV
328
                ->create($context['resource_class'], $attribute, $options);
×
329

330
            // prevent declaring $attribute as attribute if it's already declared as relationship
UNCOV
331
            $isRelationship = false;
×
332

UNCOV
333
            if (!method_exists(PropertyInfoExtractor::class, 'getType')) {
×
334
                $types = $propertyMetadata->getBuiltinTypes() ?? [];
×
335

336
                foreach ($types as $type) {
×
337
                    $isOne = $isMany = false;
×
338

339
                    if ($type->isCollection()) {
×
340
                        $collectionValueType = $type->getCollectionValueTypes()[0] ?? null;
×
341
                        $isMany = $collectionValueType && ($className = $collectionValueType->getClassName()) && $this->resourceClassResolver->isResourceClass($className);
×
342
                    } else {
343
                        $isOne = ($className = $type->getClassName()) && $this->resourceClassResolver->isResourceClass($className);
×
344
                    }
345

346
                    if (!isset($className) || !$isOne && !$isMany) {
×
347
                        // don't declare it as an attribute too quick: maybe the next type is a valid resource
348
                        continue;
×
349
                    }
350

351
                    $relation = [
×
352
                        'name' => $attribute,
×
353
                        'type' => $this->getResourceShortName($className),
×
354
                        'cardinality' => $isOne ? 'one' : 'many',
×
355
                    ];
×
356

357
                    // if we specify the uriTemplate, generates its value for link definition
358
                    // @see ApiPlatform\Serializer\AbstractItemNormalizer:getAttributeValue logic for intentional duplicate content
359
                    if ($itemUriTemplate = $propertyMetadata->getUriTemplate()) {
×
360
                        $attributeValue = $this->propertyAccessor->getValue($object, $attribute);
×
361
                        $resourceClass = $this->resourceClassResolver->getResourceClass($attributeValue, $className);
×
362
                        $childContext = $this->createChildContext($context, $attribute, $format);
×
363
                        unset($childContext['iri'], $childContext['uri_variables'], $childContext['resource_class'], $childContext['operation']);
×
364

365
                        $operation = $this->resourceMetadataCollectionFactory->create($resourceClass)->getOperation(
×
366
                            operationName: $itemUriTemplate,
×
367
                            httpOperation: true
×
368
                        );
×
369

370
                        $components['links'][$attribute] = $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_PATH, $operation, $childContext);
×
371
                    }
372

373
                    $components['relationships'][] = $relation;
×
374
                    $isRelationship = true;
×
375
                }
376
            } else {
UNCOV
377
                if ($type = $propertyMetadata->getNativeType()) {
×
378
                    /** @var class-string|null $className */
UNCOV
379
                    $className = null;
×
380

UNCOV
381
                    $typeIsResourceClass = function (Type $type) use (&$className): bool {
×
UNCOV
382
                        return $type instanceof ObjectType && $this->resourceClassResolver->isResourceClass($className = $type->getClassName());
×
UNCOV
383
                    };
×
384

UNCOV
385
                    foreach ($type instanceof CompositeTypeInterface ? $type->getTypes() : [$type] as $t) {
×
UNCOV
386
                        $isOne = $isMany = false;
×
387

UNCOV
388
                        if (TypeHelper::getCollectionValueType($t)?->isSatisfiedBy($typeIsResourceClass)) {
×
UNCOV
389
                            $isMany = true;
×
UNCOV
390
                        } elseif ($t->isSatisfiedBy($typeIsResourceClass)) {
×
391
                            $isOne = true;
×
392
                        }
393

UNCOV
394
                        if (!$className || (!$isOne && !$isMany)) {
×
395
                            // don't declare it as an attribute too quick: maybe the next type is a valid resource
UNCOV
396
                            continue;
×
397
                        }
398

UNCOV
399
                        $relation = [
×
UNCOV
400
                            'name' => $attribute,
×
UNCOV
401
                            'type' => $this->getResourceShortName($className),
×
UNCOV
402
                            'cardinality' => $isOne ? 'one' : 'many',
×
UNCOV
403
                        ];
×
404

405
                        // if we specify the uriTemplate, generates its value for link definition
406
                        // @see ApiPlatform\Serializer\AbstractItemNormalizer:getAttributeValue logic for intentional duplicate content
UNCOV
407
                        if ($itemUriTemplate = $propertyMetadata->getUriTemplate()) {
×
408
                            $attributeValue = $this->propertyAccessor->getValue($object, $attribute);
×
409
                            $resourceClass = $this->resourceClassResolver->getResourceClass($attributeValue, $className);
×
410
                            $childContext = $this->createChildContext($context, $attribute, $format);
×
411
                            unset($childContext['iri'], $childContext['uri_variables'], $childContext['resource_class'], $childContext['operation']);
×
412

413
                            $operation = $this->resourceMetadataCollectionFactory->create($resourceClass)->getOperation(
×
414
                                operationName: $itemUriTemplate,
×
415
                                httpOperation: true
×
416
                            );
×
417

418
                            $components['links'][$attribute] = $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_PATH, $operation, $childContext);
×
419
                        }
420

UNCOV
421
                        $components['relationships'][] = $relation;
×
UNCOV
422
                        $isRelationship = true;
×
423
                    }
424
                }
425
            }
426

427
            // if all types are not relationships, declare it as an attribute
UNCOV
428
            if (!$isRelationship) {
×
UNCOV
429
                $components['attributes'][] = $attribute;
×
430
            }
431
        }
432

UNCOV
433
        if (false !== $context['cache_key']) {
×
UNCOV
434
            $this->componentsCache[$cacheKey] = $components;
×
435
        }
436

UNCOV
437
        return $components;
×
438
    }
439

440
    /**
441
     * Populates relationships keys.
442
     *
443
     * @throws UnexpectedValueException
444
     */
445
    private function getPopulatedRelations(object $object, ?string $format, array $context, array $relationships): array
446
    {
UNCOV
447
        $data = [];
×
448

UNCOV
449
        if (!isset($context['resource_class'])) {
×
450
            return $data;
×
451
        }
452

UNCOV
453
        unset($context['api_included']);
×
UNCOV
454
        foreach ($relationships as $relationshipDataArray) {
×
UNCOV
455
            $relationshipName = $relationshipDataArray['name'];
×
456

UNCOV
457
            $attributeValue = $this->getAttributeValue($object, $relationshipName, $format, $context);
×
458

UNCOV
459
            if ($this->nameConverter) {
×
UNCOV
460
                $relationshipName = $this->nameConverter->normalize($relationshipName, $context['resource_class'], self::FORMAT, $context);
×
461
            }
462

UNCOV
463
            $data[$relationshipName] = [
×
UNCOV
464
                'data' => [],
×
UNCOV
465
            ];
×
466

UNCOV
467
            if (!$attributeValue) {
×
UNCOV
468
                continue;
×
469
            }
470

471
            // Many to one relationship
472
            if ('one' === $relationshipDataArray['cardinality']) {
×
473
                unset($attributeValue['data']['attributes']);
×
474
                $data[$relationshipName] = $attributeValue;
×
475

476
                continue;
×
477
            }
478

479
            // Many to many relationship
480
            foreach ($attributeValue as $attributeValueElement) {
×
481
                if (!isset($attributeValueElement['data'])) {
×
482
                    throw new UnexpectedValueException(\sprintf('The JSON API attribute \'%s\' must contain a "data" key.', $relationshipName));
×
483
                }
484
                unset($attributeValueElement['data']['attributes']);
×
485
                $data[$relationshipName]['data'][] = $attributeValueElement['data'];
×
486
            }
487
        }
488

UNCOV
489
        return $data;
×
490
    }
491

492
    /**
493
     * Populates included keys.
494
     */
495
    private function getRelatedResources(object $object, ?string $format, array $context, array $relationships): array
496
    {
UNCOV
497
        if (!isset($context['api_included'])) {
×
UNCOV
498
            return [];
×
499
        }
500

501
        $included = [];
×
502
        foreach ($relationships as $relationshipDataArray) {
×
503
            $relationshipName = $relationshipDataArray['name'];
×
504

505
            if (!$this->shouldIncludeRelation($relationshipName, $context)) {
×
506
                continue;
×
507
            }
508

509
            $relationContext = $context;
×
510
            $relationContext['api_included'] = $this->getIncludedNestedResources($relationshipName, $context);
×
511

512
            $attributeValue = $this->getAttributeValue($object, $relationshipName, $format, $relationContext);
×
513

514
            if (!$attributeValue) {
×
515
                continue;
×
516
            }
517

518
            // Many to many relationship
519
            $attributeValues = $attributeValue;
×
520
            // Many to one relationship
521
            if ('one' === $relationshipDataArray['cardinality']) {
×
522
                $attributeValues = [$attributeValue];
×
523
            }
524

525
            foreach ($attributeValues as $attributeValueElement) {
×
526
                if (isset($attributeValueElement['data'])) {
×
527
                    $this->addIncluded($attributeValueElement['data'], $included, $context);
×
528
                    if (isset($attributeValueElement['included']) && \is_array($attributeValueElement['included'])) {
×
529
                        foreach ($attributeValueElement['included'] as $include) {
×
530
                            $this->addIncluded($include, $included, $context);
×
531
                        }
532
                    }
533
                }
534
            }
535
        }
536

537
        return $included;
×
538
    }
539

540
    /**
541
     * Add data to included array if it's not already included.
542
     */
543
    private function addIncluded(array $data, array &$included, array &$context): void
544
    {
545
        if (isset($data['id']) && !\in_array($data['id'], $context['api_included_resources'], true)) {
×
546
            $included[] = $data;
×
547
            // Track already included resources
548
            $context['api_included_resources'][] = $data['id'];
×
549
        }
550
    }
551

552
    /**
553
     * Figures out if the relationship is in the api_included hash or has included nested resources (path).
554
     */
555
    private function shouldIncludeRelation(string $relationshipName, array $context): bool
556
    {
557
        $normalizedName = $this->nameConverter ? $this->nameConverter->normalize($relationshipName, $context['resource_class'], self::FORMAT, $context) : $relationshipName;
×
558

559
        return \in_array($normalizedName, $context['api_included'], true) || \count($this->getIncludedNestedResources($relationshipName, $context)) > 0;
×
560
    }
561

562
    /**
563
     * Returns the names of the nested resources from a path relationship.
564
     */
565
    private function getIncludedNestedResources(string $relationshipName, array $context): array
566
    {
567
        $normalizedName = $this->nameConverter ? $this->nameConverter->normalize($relationshipName, $context['resource_class'], self::FORMAT, $context) : $relationshipName;
×
568

569
        $filtered = array_filter($context['api_included'] ?? [], static fn (string $included): bool => str_starts_with($included, $normalizedName.'.'));
×
570

571
        return array_map(static fn (string $nested): string => substr($nested, strpos($nested, '.') + 1), $filtered);
×
572
    }
573

574
    // TODO: this code is similar to the one used in JsonLd
575
    private function getResourceShortName(string $resourceClass): string
576
    {
UNCOV
577
        if ($this->resourceClassResolver->isResourceClass($resourceClass)) {
×
UNCOV
578
            $resourceMetadata = $this->resourceMetadataCollectionFactory->create($resourceClass);
×
579

UNCOV
580
            return $resourceMetadata->getOperation()->getShortName();
×
581
        }
582

UNCOV
583
        return (new \ReflectionClass($resourceClass))->getShortName();
×
584
    }
585
}
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