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

api-platform / core / 14635100171

24 Apr 2025 06:39AM UTC coverage: 8.271% (+0.02%) from 8.252%
14635100171

Pull #6904

github

web-flow
Merge c9cefd82e into a3e5e53ea
Pull Request #6904: feat(graphql): added support for graphql subscriptions to work for actions

0 of 73 new or added lines in 3 files covered. (0.0%)

1999 existing lines in 144 files now uncovered.

13129 of 158728 relevant lines covered (8.27%)

13.6 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
    }
1,180✔
45

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

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

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

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

74
        return $context;
3✔
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);
20✔
84
        if (null === $shortName = $operation->getShortName()) {
20✔
85
            return [];
×
86
        }
87

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

93
            return $context;
5✔
94
        }
95

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

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

109
        return $this->urlGenerator->generate('api_jsonld_context', ['shortName' => $resourceMetadata->getShortName()], $referenceType ?? UrlGeneratorInterface::ABS_PATH);
669✔
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);
49✔
118
        $operation = $context['operation'] ?? new Get(
49✔
119
            shortName: (new \ReflectionClass($outputClass))->getShortName(),
49✔
120
            normalizationContext: [
49✔
121
                self::HYDRA_CONTEXT_HAS_PREFIX => $context[self::HYDRA_CONTEXT_HAS_PREFIX] ?? $this->defaultContext[self::HYDRA_CONTEXT_HAS_PREFIX] ?? true,
49✔
122
                'groups' => [],
49✔
123
            ],
49✔
124
            denormalizationContext: [
49✔
125
                'groups' => [],
49✔
126
            ]
49✔
127
        );
49✔
128
        $shortName = $operation->getShortName();
49✔
129

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

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

146
        if ($context['has_context'] ?? false) {
49✔
147
            unset($jsonLdContext['@context']);
33✔
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'])) {
49✔
152
            $jsonLdContext['@type'] = $this->resourceMetadataFactory->create($this->getObjectClass($context['api_resource']))[0]->getShortName();
4✔
153
        }
154

155
        return $jsonLdContext;
49✔
156
    }
157

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

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

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

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

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

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

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

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

197
        return $context;
64✔
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

© 2025 Coveralls, Inc