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

api-platform / core / 13203378522

07 Feb 2025 03:56PM UTC coverage: 8.501% (+0.7%) from 7.837%
13203378522

push

github

soyuka
Merge 4.1

111 of 490 new or added lines in 51 files covered. (22.65%)

5590 existing lines in 163 files now uncovered.

13345 of 156987 relevant lines covered (8.5%)

22.88 hits per line

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

98.75
/src/JsonLd/ContextBuilder.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\JsonLd;
15

16
use ApiPlatform\JsonLd\Serializer\HydraPrefixTrait;
17
use ApiPlatform\Metadata\Get;
18
use ApiPlatform\Metadata\HttpOperation;
19
use ApiPlatform\Metadata\IriConverterInterface;
20
use ApiPlatform\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
21
use ApiPlatform\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
22
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
23
use ApiPlatform\Metadata\Resource\Factory\ResourceNameCollectionFactoryInterface;
24
use ApiPlatform\Metadata\UrlGeneratorInterface;
25
use ApiPlatform\Metadata\Util\ClassInfoTrait;
26
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
27

28
/**
29
 * {@inheritdoc}
30
 *
31
 * @author Kévin Dunglas <dunglas@gmail.com>
32
 */
33
final class ContextBuilder implements AnonymousContextBuilderInterface
34
{
35
    use ClassInfoTrait;
36
    use HydraPrefixTrait;
37

38
    public const FORMAT = 'jsonld';
39
    public const HYDRA_PREFIX = 'hydra:';
40
    public const HYDRA_CONTEXT_HAS_PREFIX = 'hydra_prefix';
41

42
    public function __construct(private readonly ResourceNameCollectionFactoryInterface $resourceNameCollectionFactory, private readonly ResourceMetadataCollectionFactoryInterface $resourceMetadataFactory, private readonly PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, private readonly PropertyMetadataFactoryInterface $propertyMetadataFactory, private readonly UrlGeneratorInterface $urlGenerator, private readonly ?IriConverterInterface $iriConverter = null, private readonly ?NameConverterInterface $nameConverter = null, private array $defaultContext = [])
43
    {
44
    }
2,024✔
45

46
    /**
47
     * {@inheritdoc}
48
     */
49
    public function getBaseContext(int $referenceType = UrlGeneratorInterface::ABS_URL): array
50
    {
51
        return [
116✔
52
            '@vocab' => $this->urlGenerator->generate('api_doc', ['_format' => self::FORMAT], UrlGeneratorInterface::ABS_URL).'#',
116✔
53
            'hydra' => self::HYDRA_NS,
116✔
54
        ];
116✔
55
    }
56

57
    /**
58
     * {@inheritdoc}
59
     */
60
    public function getEntrypointContext(int $referenceType = UrlGeneratorInterface::ABS_PATH): array
61
    {
62
        $context = $this->getBaseContext($referenceType);
4✔
63

64
        foreach ($this->resourceNameCollectionFactory->create() as $resourceClass) {
4✔
65
            $shortName = $this->resourceMetadataFactory->create($resourceClass)[0]->getShortName();
4✔
66
            $resourceName = lcfirst($shortName);
4✔
67

68
            $context[$resourceName] = [
4✔
69
                '@id' => 'Entrypoint/'.$resourceName,
4✔
70
                '@type' => '@id',
4✔
71
            ];
4✔
72
        }
73

74
        return $context;
4✔
75
    }
76

77
    /**
78
     * {@inheritdoc}
79
     */
80
    public function getResourceContext(string $resourceClass, int $referenceType = UrlGeneratorInterface::ABS_PATH): array
81
    {
82
        /** @var HttpOperation $operation */
83
        $operation = $this->resourceMetadataFactory->create($resourceClass)->getOperation(null, false, true);
26✔
84
        if (null === $shortName = $operation->getShortName()) {
26✔
85
            return [];
×
86
        }
87

88
        $context = $operation->getNormalizationContext();
26✔
89
        if ($context['iri_only'] ?? false) {
26✔
90
            $context = $this->getBaseContext($referenceType);
8✔
91
            $context[$this->getHydraPrefix($context).'member']['@type'] = '@id';
8✔
92

93
            return $context;
8✔
94
        }
95

96
        return $this->getResourceContextWithShortname($resourceClass, $referenceType, $shortName, $operation);
18✔
97
    }
98

99
    /**
100
     * {@inheritdoc}
101
     */
102
    public function getResourceContextUri(string $resourceClass, ?int $referenceType = null): string
103
    {
104
        $resourceMetadata = $this->resourceMetadataFactory->create($resourceClass)[0];
1,160✔
105
        if (null === $referenceType) {
1,160✔
106
            $referenceType = $resourceMetadata->getUrlGenerationStrategy();
1,160✔
107
        }
108

109
        return $this->urlGenerator->generate('api_jsonld_context', ['shortName' => $resourceMetadata->getShortName()], $referenceType ?? UrlGeneratorInterface::ABS_PATH);
1,160✔
110
    }
111

112
    /**
113
     * {@inheritdoc}
114
     */
115
    public function getAnonymousResourceContext(object $object, array $context = [], int $referenceType = UrlGeneratorInterface::ABS_PATH): array
116
    {
117
        $outputClass = $this->getObjectClass($object);
86✔
118
        $operation = $context['operation'] ?? new Get(
86✔
119
            shortName: (new \ReflectionClass($outputClass))->getShortName(),
86✔
120
            normalizationContext: [
86✔
121
                self::HYDRA_CONTEXT_HAS_PREFIX => $context[self::HYDRA_CONTEXT_HAS_PREFIX] ?? $this->defaultContext[self::HYDRA_CONTEXT_HAS_PREFIX] ?? true,
86✔
122
                'groups' => [],
86✔
123
            ],
86✔
124
            denormalizationContext: [
86✔
125
                'groups' => [],
86✔
126
            ]
86✔
127
        );
86✔
128
        $shortName = $operation->getShortName();
86✔
129

130
        $jsonLdContext = [
86✔
131
            '@context' => $this->getResourceContextWithShortname(
86✔
132
                $outputClass,
86✔
133
                $referenceType,
86✔
134
                $shortName,
86✔
135
                $operation
86✔
136
            ),
86✔
137
            '@type' => $shortName,
86✔
138
        ];
86✔
139

140
        if (isset($context['iri'])) {
86✔
141
            $jsonLdContext['@id'] = $context['iri'];
6✔
142
        } elseif (true === ($context['gen_id'] ?? true) && $this->iriConverter) {
80✔
143
            $jsonLdContext['@id'] = $this->iriConverter->getIriFromResource($object);
77✔
144
        }
145

146
        if ($context['has_context'] ?? false) {
86✔
147
            unset($jsonLdContext['@context']);
63✔
148
        }
149

150
        // here the object can be different from the resource given by the $context['api_resource'] value
151
        if (isset($context['api_resource'])) {
86✔
152
            $jsonLdContext['@type'] = $this->resourceMetadataFactory->create($this->getObjectClass($context['api_resource']))[0]->getShortName();
4✔
153
        }
154

155
        return $jsonLdContext;
86✔
156
    }
157

158
    private function getResourceContextWithShortname(string $resourceClass, int $referenceType, string $shortName, ?HttpOperation $operation = null): array
159
    {
160
        $context = $this->getBaseContext($referenceType);
104✔
161
        $propertyContext = $operation ? ['normalization_groups' => $operation->getNormalizationContext()['groups'] ?? null, 'denormalization_groups' => $operation->getDenormalizationContext()['groups'] ?? null] : ['normalization_groups' => [], 'denormalization_groups' => []];
104✔
162

163
        foreach ($this->propertyNameCollectionFactory->create($resourceClass) as $propertyName) {
104✔
164
            $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $propertyName, $propertyContext);
103✔
165

166
            if ($propertyMetadata->isIdentifier() && true !== $propertyMetadata->isWritable()) {
103✔
167
                continue;
36✔
168
            }
169

170
            $convertedName = $this->nameConverter ? $this->nameConverter->normalize($propertyName, $resourceClass, self::FORMAT) : $propertyName;
103✔
171
            $jsonldContext = $propertyMetadata->getJsonldContext() ?? [];
103✔
172

173
            if ($id = $propertyMetadata->getIris()) {
103✔
174
                $id = 1 === (is_countable($id) ? \count($id) : 0) ? $id[0] : $id;
2✔
175
            }
176

177
            if (!$id) {
103✔
178
                $id = \sprintf('%s/%s', $shortName, $convertedName);
103✔
179
            }
180

181
            if (false === $propertyMetadata->isReadableLink()) {
103✔
182
                $jsonldContext += [
2✔
183
                    '@id' => $id,
2✔
184
                    '@type' => '@id',
2✔
UNCOV
185
                ];
2✔
186
            }
187

188
            if (empty($jsonldContext)) {
103✔
189
                $context[$convertedName] = $id;
97✔
190
            } else {
191
                $context[$convertedName] = $jsonldContext + [
8✔
192
                    '@id' => $id,
8✔
193
                ];
8✔
194
            }
195
        }
196

197
        return $context;
104✔
198
    }
199
}
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

© 2026 Coveralls, Inc