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

api-platform / core / 14306224552

07 Apr 2025 09:55AM UTC coverage: 8.425% (+1.2%) from 7.202%
14306224552

push

github

web-flow
fix(metadata): yaml link security (#7066)

1 of 3 new or added lines in 2 files covered. (33.33%)

2165 existing lines in 153 files now uncovered.

13288 of 157729 relevant lines covered (8.42%)

22.89 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,059✔
35

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

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

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

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

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

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

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

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

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

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

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

93
        return $resourceMetadataCollection;
133✔
94
    }
95

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

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

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

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

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

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

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

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

147
            return $operation;
123✔
148
        }
149

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

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

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

165
            if (\count($variables) !== \count($uriVariables)) {
60✔
166
                if ($hasUserConfiguredUriVariables) {
41✔
167
                    return $operation;
14✔
168
                }
169

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

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

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

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

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

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

UNCOV
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() ?? []);
126✔
212

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

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

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

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

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

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

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

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