• 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

89.38
/src/Metadata/Resource/Factory/UriTemplateResourceMetadataCollectionFactory.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\Metadata\Resource\Factory;
15

16
use ApiPlatform\Metadata\ApiResource;
17
use ApiPlatform\Metadata\CollectionOperationInterface;
18
use ApiPlatform\Metadata\HttpOperation;
19
use ApiPlatform\Metadata\Link;
20
use ApiPlatform\Metadata\Operation\PathSegmentNameGeneratorInterface;
21
use ApiPlatform\Metadata\Operations;
22
use ApiPlatform\Metadata\Resource\ResourceMetadataCollection;
23
use Symfony\Component\Routing\Route;
24

25
/**
26
 * @author Antoine Bluchet <soyuka@gmail.com>
27
 */
28
final class UriTemplateResourceMetadataCollectionFactory implements ResourceMetadataCollectionFactoryInterface
29
{
30
    use OperationDefaultsTrait;
31

32
    public function __construct(private readonly LinkFactoryInterface $linkFactory, private readonly PathSegmentNameGeneratorInterface $pathSegmentNameGenerator, private readonly ?ResourceMetadataCollectionFactoryInterface $decorated = null)
33
    {
34
    }
1,214✔
35

36
    /**
37
     * {@inheritdoc}
38
     */
39
    public function create(string $resourceClass): ResourceMetadataCollection
40
    {
41
        $resourceMetadataCollection = new ResourceMetadataCollection($resourceClass);
101✔
42
        if ($this->decorated) {
101✔
43
            $resourceMetadataCollection = $this->decorated->create($resourceClass);
101✔
44
        }
45

46
        foreach ($resourceMetadataCollection as $i => $resource) {
101✔
47
            /** @var ApiResource $resource */
48
            $resource = $this->configureUriVariables($resource);
96✔
49
            if ($resource->getUriTemplate()) {
96✔
50
                $resourceMetadataCollection[$i] = $resource->withExtraProperties($resource->getExtraProperties() + ['user_defined_uri_template' => true]);
18✔
51
            }
52

53
            $operations = new Operations();
96✔
54
            foreach ($resource->getOperations() ?? new Operations() as $key => $operation) {
96✔
55
                /** @var HttpOperation */
56
                $operation = $this->configureUriVariables($operation);
96✔
57

58
                if (
59
                    $operation->getUriTemplate()
96✔
60
                    && !($operation->getExtraProperties()['generated_operation'] ?? false)
96✔
61
                ) {
62
                    $operation = $operation->withExtraProperties($operation->getExtraProperties() + ['user_defined_uri_template' => true]);
45✔
63
                    if (!$operation->getName()) {
45✔
64
                        $operation = $operation->withName($key);
41✔
65
                    }
66

67
                    $operations->add($key, $operation);
45✔
68
                    continue;
45✔
69
                }
70

71
                if ($routeName = $operation->getRouteName()) {
85✔
UNCOV
72
                    if (!$operation->getName()) {
1✔
73
                        $operation = $operation->withName($routeName);
×
74
                    }
75

UNCOV
76
                    $operations->add($operation->getName(), $operation);
1✔
UNCOV
77
                    continue;
1✔
78
                }
79

80
                $operation = $operation->withUriTemplate($this->generateUriTemplate($operation));
85✔
81

82
                if (!$operation->getName()) {
85✔
83
                    $operation = $operation->withName($this->getDefaultOperationName($operation, $resourceClass));
85✔
84
                }
85

86
                $operations->add($operation->getName(), $operation);
85✔
87
            }
88

89
            $resource = $resource->withOperations($operations);
96✔
90
            $resourceMetadataCollection[$i] = $resource;
96✔
91
        }
92

93
        return $resourceMetadataCollection;
101✔
94
    }
95

96
    private function generateUriTemplate(HttpOperation $operation): string
97
    {
98
        $uriTemplate = $operation->getUriTemplate() ?? \sprintf('/%s', $this->pathSegmentNameGenerator->getSegmentName($operation->getShortName()));
85✔
99
        $uriVariables = $operation->getUriVariables() ?? [];
85✔
100

101
        if (str_ends_with($uriTemplate, '{._format}')) {
85✔
102
            $uriTemplate = substr($uriTemplate, 0, -10);
×
103
        }
104

105
        if ($parameters = array_keys($uriVariables)) {
85✔
106
            foreach ($parameters as $parameterName) {
81✔
107
                $part = \sprintf('/{%s}', $parameterName);
81✔
108
                if (!str_contains($uriTemplate, $part)) {
81✔
109
                    $uriTemplate .= \sprintf('/{%s}', $parameterName);
74✔
110
                }
111
            }
112
        }
113

114
        return \sprintf('%s%s', $uriTemplate, '{._format}');
85✔
115
    }
116

117
    private function configureUriVariables(ApiResource|HttpOperation $operation): ApiResource|HttpOperation
118
    {
119
        // We will generate the collection route, don't initialize variables here
120
        if ($operation instanceof HttpOperation && (
96✔
121
            [] === $operation->getUriVariables()
96✔
122
            || (
96✔
123
                $operation instanceof CollectionOperationInterface
96✔
124
                && null === $operation->getUriTemplate()
96✔
125
            )
96✔
126
        )) {
127
            if (null === $operation->getUriVariables()) {
64✔
128
                return $operation;
64✔
129
            }
130

UNCOV
131
            return $this->normalizeUriVariables($operation);
1✔
132
        }
133

134
        $hasUserConfiguredUriVariables = !($operation->getExtraProperties()['is_legacy_resource_metadata'] ?? false);
96✔
135
        if (!$operation->getUriVariables()) {
96✔
136
            $hasUserConfiguredUriVariables = false;
94✔
137
            $operation = $operation->withUriVariables($this->transformLinksToUriVariables($this->linkFactory->createLinksFromIdentifiers($operation)));
94✔
138
        }
139

140
        $operation = $this->normalizeUriVariables($operation);
96✔
141

142
        if (!($uriTemplate = $operation->getUriTemplate())) {
96✔
143
            if ($operation instanceof HttpOperation && 'POST' === $operation->getMethod()) {
94✔
144
                return $operation->withUriVariables([]);
41✔
145
            }
146

147
            return $operation;
94✔
148
        }
149

150
        foreach ($uriVariables = $operation->getUriVariables() as $parameterName => $l) {
47✔
151
            $link = null === $l->getFromClass() ? $l->withFromClass($operation->getClass()) : $l;
38✔
152
            $uriVariables[$parameterName] = $this->linkFactory->completeLink($link);
38✔
153
        }
154
        $operation = $operation->withUriVariables($uriVariables);
47✔
155

156
        if (str_ends_with($uriTemplate, '{._format}') || str_ends_with($uriTemplate, '.{_format}')) {
47✔
157
            $uriTemplate = substr($uriTemplate, 0, -10);
23✔
158
        }
159

160
        // TODO: move this to the Symfony bridge
161
        if (class_exists(Route::class)) {
47✔
162
            $route = (new Route($uriTemplate))->compile();
47✔
163
            $variables = $route->getPathVariables();
47✔
164

165
            if (\count($variables) !== \count($uriVariables)) {
47✔
166
                if ($hasUserConfiguredUriVariables) {
33✔
167
                    return $operation;
9✔
168
                }
169

170
                $newUriVariables = [];
29✔
171
                foreach ($variables as $variable) {
29✔
172
                    if (isset($uriVariables[$variable])) {
8✔
173
                        $newUriVariables[$variable] = $uriVariables[$variable];
×
174
                        continue;
×
175
                    }
176

177
                    $newUriVariables[$variable] = (new Link())
8✔
178
                        ->withFromClass($operation->getClass())
8✔
179
                        ->withIdentifiers([property_exists($operation->getClass(), $variable) ? $variable : 'id'])
8✔
180
                        ->withParameterName($variable);
8✔
181
                }
182

183
                return $operation->withUriVariables($newUriVariables);
29✔
184
            }
185

186
            // When an operation is generated we need to find properties matching it's uri variables
187
            if (!($operation->getExtraProperties()['generated_operation'] ?? false) || !$this->linkFactory instanceof PropertyLinkFactoryInterface) {
35✔
188
                return $operation;
35✔
189
            }
190

UNCOV
191
            $diff = array_diff($variables, array_keys($uriVariables));
1✔
UNCOV
192
            if (0 === \count($diff)) {
1✔
UNCOV
193
                return $operation;
1✔
194
            }
195

196
            // We generated this operation but there're some missing identifiers
197
            $uriVariables = 'POST' === $operation->getMethod() || $operation instanceof CollectionOperationInterface ? [] : $operation->getUriVariables();
×
198

199
            foreach ($diff as $key) {
×
200
                $uriVariables[$key] = $this->linkFactory->createLinkFromProperty($operation, $key);
×
201
            }
202

203
            return $operation->withUriVariables($uriVariables);
×
204
        }
205

206
        return $operation;
×
207
    }
208

209
    private function normalizeUriVariables(ApiResource|HttpOperation $operation): ApiResource|HttpOperation
210
    {
211
        $uriVariables = (array) ($operation->getUriVariables() ?? []);
96✔
212

213
        $normalizedUriVariables = [];
96✔
214
        $resourceClass = $operation->getClass();
96✔
215

216
        foreach ($uriVariables as $parameterName => $uriVariable) {
96✔
217
            $normalizedParameterName = $parameterName;
85✔
218
            $normalizedUriVariable = $uriVariable;
85✔
219

220
            if (\is_int($normalizedParameterName)) {
85✔
221
                $normalizedParameterName = $normalizedUriVariable;
7✔
222
            }
223
            if (\is_string($normalizedUriVariable)) {
85✔
224
                $normalizedUriVariable = (new Link())->withIdentifiers([$normalizedUriVariable])->withFromClass($resourceClass);
7✔
225
            }
226
            if (\is_array($normalizedUriVariable)) {
85✔
UNCOV
227
                if (!isset($normalizedUriVariable['from_class']) && !isset($normalizedUriVariable['expanded_value'])) {
1✔
228
                    if (2 !== \count($normalizedUriVariable)) {
×
229
                        throw new \LogicException("The uriVariables shortcut syntax needs to be the tuple: 'uriVariable' => [fromClass, fromProperty]");
×
230
                    }
231
                    $normalizedUriVariable = (new Link())->withFromProperty($normalizedUriVariable[1])->withFromClass($normalizedUriVariable[0]);
×
232
                } else {
UNCOV
233
                    $normalizedUriVariable = new Link($normalizedParameterName, $normalizedUriVariable['from_property'] ?? null, $normalizedUriVariable['to_property'] ?? null, $normalizedUriVariable['from_class'] ?? null, $normalizedUriVariable['to_class'] ?? null, $normalizedUriVariable['identifiers'] ?? null, $normalizedUriVariable['composite_identifier'] ?? null, $normalizedUriVariable['expanded_value'] ?? null, $normalizedUriVariable['security'] ?? null);
1✔
234
                }
235
            }
236

237
            $normalizedUriVariable = $normalizedUriVariable->withParameterName($normalizedParameterName);
85✔
238
            $normalizedUriVariables[$normalizedParameterName] = $normalizedUriVariable;
85✔
239
        }
240

241
        return $operation->withUriVariables($normalizedUriVariables);
96✔
242
    }
243

244
    /**
245
     * @param Link[] $links
246
     *
247
     * @return array<string, Link>
248
     */
249
    private function transformLinksToUriVariables(array $links): array
250
    {
251
        $uriVariables = [];
94✔
252

253
        foreach ($links as $link) {
94✔
254
            $uriVariables[$link->getParameterName()] = $link;
81✔
255
        }
256

257
        return $uriVariables;
94✔
258
    }
259
}
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