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

api-platform / core / 13814792797

12 Mar 2025 03:09PM UTC coverage: 5.889% (-1.4%) from 7.289%
13814792797

Pull #7012

github

web-flow
Merge 199d44919 into 284937039
Pull Request #7012: doc: comment typo in ApiResource.php

10048 of 170615 relevant lines covered (5.89%)

5.17 hits per line

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

81.42
/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
    }
465✔
35

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

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

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

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

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

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

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

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

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

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

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

93
        return $resourceMetadataCollection;
84✔
94
    }
95

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

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

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

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

131
            return $this->normalizeUriVariables($operation);
×
132
        }
133

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

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

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

147
            return $operation;
81✔
148
        }
149

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

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

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

165
            if (\count($variables) !== \count($uriVariables)) {
51✔
166
                if ($hasUserConfiguredUriVariables) {
39✔
167
                    return $operation;
6✔
168
                }
169

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

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

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

191
            $diff = array_diff($variables, array_keys($uriVariables));
×
192
            if (0 === \count($diff)) {
×
193
                return $operation;
×
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() ?? []);
81✔
212

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

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

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

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

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

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

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

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