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

api-platform / core / 13175309672

06 Feb 2025 09:04AM UTC coverage: 7.663% (-0.2%) from 7.841%
13175309672

push

github

web-flow
fix: ensure template files have a tpl file extension (#6826) (#6829)

2 of 5 new or added lines in 4 files covered. (40.0%)

3676 existing lines in 122 files now uncovered.

13073 of 170593 relevant lines covered (7.66%)

27.3 hits per line

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

94.69
/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
    }
2,729✔
35

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

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

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

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

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

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

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

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

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

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

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

93
        return $resourceMetadataCollection;
174✔
94
    }
95

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

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

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

114
        return \sprintf('%s%s', $uriTemplate, '{._format}');
146✔
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 && (
163✔
121
            [] === $operation->getUriVariables()
163✔
122
            || (
163✔
123
                $operation instanceof CollectionOperationInterface
163✔
124
                && null === $operation->getUriTemplate()
163✔
125
            )
163✔
126
        )) {
127
            if (null === $operation->getUriVariables()) {
112✔
128
                return $operation;
112✔
129
            }
130

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

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

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

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

147
            return $operation;
158✔
148
        }
149

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

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

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

165
            if (\count($variables) !== \count($uriVariables)) {
90✔
166
                if ($hasUserConfiguredUriVariables) {
61✔
167
                    return $operation;
21✔
168
                }
169

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

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

183
                return $operation->withUriVariables($newUriVariables);
47✔
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) {
75✔
188
                return $operation;
75✔
189
            }
190

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

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

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

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

206
        return $operation;
×
207
    }
208

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

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

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

220
            if (\is_int($normalizedParameterName)) {
145✔
221
                $normalizedParameterName = $normalizedUriVariable;
15✔
222
            }
223
            if (\is_string($normalizedUriVariable)) {
145✔
224
                $normalizedUriVariable = (new Link())->withIdentifiers([$normalizedUriVariable])->withFromClass($resourceClass);
15✔
225
            }
226
            if (\is_array($normalizedUriVariable)) {
145✔
UNCOV
227
                if (!isset($normalizedUriVariable['from_class']) && !isset($normalizedUriVariable['expanded_value'])) {
4✔
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);
4✔
234
                }
235
            }
236

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

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

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

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

257
        return $uriVariables;
158✔
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