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

api-platform / core / 20135591630

11 Dec 2025 01:58PM UTC coverage: 25.294% (+0.002%) from 25.292%
20135591630

push

github

web-flow
feat(symfony): isGranted before provider (#7500)

35 of 41 new or added lines in 3 files covered. (85.37%)

193 existing lines in 6 files now uncovered.

14672 of 58005 relevant lines covered (25.29%)

29.35 hits per line

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

91.11
/src/Metadata/Resource/Factory/ParameterResourceMetadataCollectionFactory.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\Doctrine\Common\Filter\PropertyAwareFilterInterface;
17
use ApiPlatform\Metadata\ApiProperty;
18
use ApiPlatform\Metadata\Exception\RuntimeException;
19
use ApiPlatform\Metadata\FilterInterface;
20
use ApiPlatform\Metadata\JsonSchemaFilterInterface;
21
use ApiPlatform\Metadata\OpenApiParameterFilterInterface;
22
use ApiPlatform\Metadata\Operation;
23
use ApiPlatform\Metadata\Parameter;
24
use ApiPlatform\Metadata\ParameterProviderFilterInterface;
25
use ApiPlatform\Metadata\Parameters;
26
use ApiPlatform\Metadata\PropertiesAwareInterface;
27
use ApiPlatform\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
28
use ApiPlatform\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
29
use ApiPlatform\Metadata\Resource\ResourceMetadataCollection;
30
use ApiPlatform\OpenApi\Model\Parameter as OpenApiParameter;
31
use ApiPlatform\Serializer\Filter\FilterInterface as SerializerFilterInterface;
32
use ApiPlatform\State\Parameter\ValueCaster;
33
use ApiPlatform\State\Util\StateOptionsTrait;
34
use Psr\Container\ContainerInterface;
35
use Psr\Log\LoggerInterface;
36
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
37
use Symfony\Component\TypeInfo\Type;
38
use Symfony\Component\TypeInfo\TypeIdentifier;
39

40
/**
41
 * Prepares Parameters documentation by reading its filter details and declaring an OpenApi parameter.
42
 */
43
final class ParameterResourceMetadataCollectionFactory implements ResourceMetadataCollectionFactoryInterface
44
{
45
    use StateOptionsTrait;
46

47
    private array $localPropertyCache = [];
48

49
    public function __construct(
50
        private readonly PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory,
51
        private readonly PropertyMetadataFactoryInterface $propertyMetadataFactory,
52
        private readonly ?ResourceMetadataCollectionFactoryInterface $decorated = null,
53
        private readonly ?ContainerInterface $filterLocator = null,
54
        private readonly ?NameConverterInterface $nameConverter = null,
55
        private readonly ?LoggerInterface $logger = null,
56
    ) {
57
    }
848✔
58

59
    public function create(string $resourceClass): ResourceMetadataCollection
60
    {
61
        $resourceMetadataCollection = $this->decorated?->create($resourceClass) ?? new ResourceMetadataCollection($resourceClass);
132✔
62

63
        foreach ($resourceMetadataCollection as $i => $resource) {
132✔
64
            $operations = $resource->getOperations();
130✔
65

66
            $internalPriority = -1;
130✔
67
            foreach ($operations as $operationName => $operation) {
130✔
68
                $parameters = $this->getDefaultParameters($operation, $resourceClass, $internalPriority);
130✔
69
                if (\count($parameters) > 0) {
130✔
70
                    $operations->add($operationName, $operation->withParameters($parameters));
36✔
71
                }
72
            }
73

74
            $resourceMetadataCollection[$i] = $resource->withOperations($operations->sort());
130✔
75

76
            if (!$graphQlOperations = $resource->getGraphQlOperations()) {
130✔
77
                continue;
64✔
78
            }
79

80
            $internalPriority = -1;
94✔
81
            foreach ($graphQlOperations as $operationName => $operation) {
94✔
82
                $parameters = $this->getDefaultParameters($operation, $resourceClass, $internalPriority);
94✔
83
                if (\count($parameters) > 0) {
94✔
84
                    $graphQlOperations[$operationName] = $operation->withParameters($parameters);
4✔
85
                }
86
            }
87

88
            $resourceMetadataCollection[$i] = $resource->withGraphQlOperations($graphQlOperations);
94✔
89
        }
90

91
        return $resourceMetadataCollection;
132✔
92
    }
93

94
    /**
95
     * @return array{propertyNames: string[], properties: array<string, ApiProperty>}
96
     */
97
    private function getProperties(string $resourceClass, ?Parameter $parameter = null): array
98
    {
99
        $k = $resourceClass.($parameter?->getProperties() ? ($parameter->getKey() ?? '') : '').(\is_string($parameter->getFilter()) ? $parameter->getFilter() : '');
36✔
100
        if (isset($this->localPropertyCache[$k])) {
36✔
101
            return $this->localPropertyCache[$k];
30✔
102
        }
103

104
        $propertyNames = [];
36✔
105
        $properties = [];
36✔
106
        foreach ($parameter?->getProperties() ?? $this->propertyNameCollectionFactory->create($resourceClass) as $property) {
36✔
107
            $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $property);
30✔
108
            if ($propertyMetadata->isReadable()) {
30✔
109
                $propertyNames[] = $property;
30✔
110
                $properties[$property] = $propertyMetadata;
30✔
111
            }
112
        }
113

114
        if (($filter = $this->getFilterInstance($parameter->getFilter())) && $filter instanceof PropertyAwareFilterInterface) {
36✔
115
            if (!method_exists($filter, 'getProperties')) { // @phpstan-ignore-line todo 5.x remove this check
16✔
116
                trigger_deprecation('api-platform/core', 'In API Platform 5.0 "%s" will implement a method named "getProperties"', PropertyAwareFilterInterface::class);
×
117
                $refl = new \ReflectionClass($filter);
×
118
                $filterProperties = $refl->hasProperty('properties') ? $refl->getProperty('properties')->getValue($filter) : [];
×
119
            } else {
120
                $filterProperties = array_keys($filter->getProperties() ?? []);
16✔
121
            }
122

123
            foreach ($filterProperties as $prop) {
16✔
124
                if (!\in_array($prop, $propertyNames, true)) {
4✔
125
                    $propertyNames[] = $this->nameConverter?->denormalize($prop) ?? $prop;
×
126
                }
127
            }
128
        }
129

130
        $this->localPropertyCache[$k] = ['propertyNames' => $propertyNames, 'properties' => $properties];
36✔
131

132
        return $this->localPropertyCache[$k];
36✔
133
    }
134

135
    private function getDefaultParameters(Operation $operation, string $resourceClass, int &$internalPriority): Parameters
136
    {
137
        $propertyNames = $properties = [];
130✔
138
        $parameters = $operation->getParameters() ?? new Parameters();
130✔
139

140
        // First loop we look for the :property placeholder and replace its key
141
        foreach ($parameters as $key => $parameter) {
130✔
142
            if (!str_contains($key, ':property')) {
36✔
143
                continue;
34✔
144
            }
145

146
            if (!$parameter->getKey()) {
8✔
147
                $parameter = $parameter->withKey($key);
8✔
148
            }
149

150
            ['propertyNames' => $propertyNames, 'properties' => $properties] = $this->getProperties($resourceClass, $parameter);
8✔
151
            $parameter = $parameter->withProperties($propertyNames);
8✔
152

153
            foreach ($propertyNames as $property) {
8✔
154
                $converted = $this->nameConverter?->denormalize($property) ?? $property;
8✔
155
                $finalKey = str_replace(':property', $converted, $key);
8✔
156
                $parameters->add(
8✔
157
                    $finalKey,
8✔
158
                    $parameter->withProperty($converted)->withKey($finalKey)
8✔
159
                );
8✔
160
            }
161

162
            $parameters->remove($key, $parameter::class);
8✔
163
        }
164

165
        foreach ($parameters as $key => $parameter) {
130✔
166
            if (!$parameter->getKey()) {
36✔
167
                $parameter = $parameter->withKey($key);
34✔
168
            }
169

170
            $filter = $this->getFilterInstance($parameter->getFilter());
36✔
171

172
            // The filter has a parameter provider
173
            if (null === $parameter->getProvider() && (($f = $parameter->getFilter()) && $f instanceof ParameterProviderFilterInterface)) {
36✔
174
                $parameter = $parameter->withProvider($f->getParameterProvider());
2✔
175
            }
176

177
            $key = $parameter->getKey();
36✔
178

179
            ['propertyNames' => $propertyNames, 'properties' => $properties] = $this->getProperties($resourceClass, $parameter);
36✔
180

181
            if ($filter instanceof PropertiesAwareInterface) {
36✔
UNCOV
182
                $parameter = $parameter->withProperties($propertyNames);
×
183
            }
184

185
            $parameter = $this->setDefaults($key, $parameter, $filter, $properties, $operation);
36✔
186
            // We don't do any type cast yet, a query parameter or an header is always a string or a list of strings
187
            if (null === $parameter->getNativeType()) {
36✔
188
                // this forces the type to be only a list
189
                if ('array' === ($parameter->getSchema()['type'] ?? null)) {
32✔
190
                    $parameter = $parameter->withNativeType(Type::list(Type::string()));
2✔
191
                } elseif ('string' === ($parameter->getSchema()['type'] ?? null)) {
32✔
192
                    $parameter = $parameter->withNativeType(Type::string());
12✔
193
                } elseif ('boolean' === ($parameter->getSchema()['type'] ?? null)) {
24✔
194
                    $parameter = $parameter->withNativeType(Type::bool());
6✔
195
                } elseif ('integer' === ($parameter->getSchema()['type'] ?? null)) {
22✔
196
                    $parameter = $parameter->withNativeType(Type::int());
2✔
197
                } elseif ('number' === ($parameter->getSchema()['type'] ?? null)) {
22✔
198
                    $parameter = $parameter->withNativeType(Type::float());
4✔
199
                } else {
200
                    $parameter = $parameter->withNativeType(Type::union(Type::string(), Type::list(Type::string())));
20✔
201
                }
202
            }
203

204
            if ($parameter->getCastToNativeType() && null === $parameter->getCastFn() && ($nativeType = $parameter->getNativeType())) {
36✔
205
                if ($nativeType->isIdentifiedBy(TypeIdentifier::BOOL)) {
4✔
206
                    $parameter = $parameter->withCastFn([ValueCaster::class, 'toBool']);
4✔
207
                }
208
                if ($nativeType->isIdentifiedBy(TypeIdentifier::INT)) {
4✔
209
                    $parameter = $parameter->withCastFn([ValueCaster::class, 'toInt']);
2✔
210
                }
211
                if ($nativeType->isIdentifiedBy(TypeIdentifier::FLOAT)) {
4✔
212
                    $parameter = $parameter->withCastFn([ValueCaster::class, 'toFloat']);
2✔
213
                }
214
            }
215

216
            $priority = $parameter->getPriority() ?? $internalPriority--;
36✔
217
            $parameters->add($key, $parameter->withPriority($priority));
36✔
218
        }
219

220
        return $parameters;
130✔
221
    }
222

223
    private function addFilterMetadata(Parameter $parameter): Parameter
224
    {
225
        if (!$filter = $this->getFilterInstance($parameter->getFilter())) {
36✔
226
            return $parameter;
18✔
227
        }
228

229
        if ($filter instanceof ParameterProviderFilterInterface) {
22✔
230
            $parameter = $parameter->withProvider($filter::getParameterProvider());
2✔
231
        }
232

233
        if (null === $parameter->getSchema() && $filter instanceof JsonSchemaFilterInterface && $schema = $filter->getSchema($parameter)) {
22✔
234
            $parameter = $parameter->withSchema($schema);
18✔
235
        }
236

237
        if (null === $parameter->getOpenApi() && $filter instanceof OpenApiParameterFilterInterface && ($openApiParameter = $filter->getOpenApiParameters($parameter))) {
22✔
238
            $parameter = $parameter->withOpenApi($openApiParameter);
12✔
239
        }
240

241
        return $parameter;
22✔
242
    }
243

244
    /**
245
     * @param array<string, ApiProperty> $properties
246
     */
247
    private function setDefaults(string $key, Parameter $parameter, ?object $filter, array $properties, Operation $operation): Parameter
248
    {
249
        if (null === $parameter->getKey()) {
36✔
UNCOV
250
            $parameter = $parameter->withKey($key);
×
251
        }
252

253
        if ($filter instanceof SerializerFilterInterface && null === $parameter->getProvider()) {
36✔
254
            $parameter = $parameter->withProvider('api_platform.serializer.filter_parameter_provider');
2✔
255
        }
256

257
        $currentKey = $key;
36✔
258
        if (null === $parameter->getProperty() && isset($properties[$key])) {
36✔
259
            $parameter = $parameter->withProperty($key);
20✔
260
        }
261

262
        if ($this->nameConverter && $property = $parameter->getProperty()) {
36✔
263
            $parameter = $parameter->withProperty($this->nameConverter->normalize($property));
26✔
264
        }
265

266
        if (isset($properties[$currentKey]) && ($eloquentRelation = ($properties[$currentKey]->getExtraProperties()['eloquent_relation'] ?? null)) && isset($eloquentRelation['foreign_key'])) {
36✔
UNCOV
267
            $parameter = $parameter->withProperty($eloquentRelation['foreign_key']);
×
268
        }
269

270
        $parameter = $this->addFilterMetadata($parameter);
36✔
271

272
        if ($filter instanceof FilterInterface) {
36✔
273
            try {
274
                return $this->getLegacyFilterMetadata($parameter, $operation, $filter);
22✔
275
            } catch (RuntimeException $exception) {
14✔
276
                $this->logger?->alert($exception->getMessage(), ['exception' => $exception]);
14✔
277

278
                return $parameter;
14✔
279
            }
280
        }
281

282
        return $parameter;
18✔
283
    }
284

285
    private function getLegacyFilterMetadata(Parameter $parameter, Operation $operation, FilterInterface $filter): Parameter
286
    {
287
        $description = $filter->getDescription($this->getStateOptionsClass($operation, $operation->getClass()));
22✔
288
        $key = $parameter->getKey();
10✔
289
        if (($schema = $description[$key]['schema'] ?? null) && null === $parameter->getSchema()) {
10✔
290
            $parameter = $parameter->withSchema($schema);
×
291
        }
292

293
        if (null === $parameter->getProperty() && ($property = $description[$key]['property'] ?? null)) {
10✔
294
            $parameter = $parameter->withProperty($property);
×
295
        }
296

297
        if (null === $parameter->getRequired() && ($required = $description[$key]['required'] ?? null)) {
10✔
298
            $parameter = $parameter->withRequired($required);
×
299
        }
300

301
        if (null === $parameter->getOpenApi() && ($openApi = $description[$key]['openapi'] ?? null) && $openApi instanceof OpenApiParameter) {
10✔
UNCOV
302
            $parameter = $parameter->withOpenApi($openApi);
×
303
        }
304

305
        return $parameter;
10✔
306
    }
307

308
    /**
309
     * TODO: 5.x use FilterInterface on Laravel eloquent filters.
310
     *
311
     * @return FilterInterface|object
312
     */
313
    private function getFilterInstance(object|string|null $filter): ?object
314
    {
315
        if (!$filter) {
36✔
316
            return null;
18✔
317
        }
318

319
        if (\is_object($filter)) {
22✔
320
            return $filter;
20✔
321
        }
322

323
        if (!$this->filterLocator->has($filter)) {
6✔
UNCOV
324
            return null;
×
325
        }
326

327
        return $this->filterLocator->get($filter);
6✔
328
    }
329
}
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