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

api-platform / core / 20001323174

07 Dec 2025 08:10AM UTC coverage: 25.292% (+0.001%) from 25.291%
20001323174

push

github

soyuka
chore: bump metadata to 4.3.x-dev

14642 of 57891 relevant lines covered (25.29%)

28.94 hits per line

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

90.98
/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
    }
834✔
58

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

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

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

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

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

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

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

91
        return $resourceMetadataCollection;
128✔
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 = [];
126✔
138
        $parameters = $operation->getParameters() ?? new Parameters();
126✔
139

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

146
            ['propertyNames' => $propertyNames, 'properties' => $properties] = $this->getProperties($resourceClass, $parameter);
8✔
147
            $parameter = $parameter->withProperties($propertyNames);
8✔
148

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

158
            $parameters->remove($key, $parameter::class);
8✔
159
        }
160

161
        foreach ($parameters as $key => $parameter) {
126✔
162
            if (!$parameter->getKey()) {
36✔
163
                $parameter = $parameter->withKey($key);
34✔
164
            }
165

166
            $filter = $this->getFilterInstance($parameter->getFilter());
36✔
167

168
            // The filter has a parameter provider
169
            if (null === $parameter->getProvider() && (($f = $parameter->getFilter()) && $f instanceof ParameterProviderFilterInterface)) {
36✔
170
                $parameter = $parameter->withProvider($f->getParameterProvider());
2✔
171
            }
172

173
            $key = $parameter->getKey() ?? $key;
36✔
174

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

177
            if ($filter instanceof PropertiesAwareInterface) {
36✔
178
                $parameter = $parameter->withProperties($propertyNames);
×
179
            }
180

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

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

212
            $priority = $parameter->getPriority() ?? $internalPriority--;
36✔
213
            $parameters->add($key, $parameter->withPriority($priority));
36✔
214
        }
215

216
        return $parameters;
126✔
217
    }
218

219
    private function addFilterMetadata(Parameter $parameter): Parameter
220
    {
221
        if (!$filter = $this->getFilterInstance($parameter->getFilter())) {
36✔
222
            return $parameter;
18✔
223
        }
224

225
        if ($filter instanceof ParameterProviderFilterInterface) {
22✔
226
            $parameter = $parameter->withProvider($filter::getParameterProvider());
2✔
227
        }
228

229
        if (null === $parameter->getSchema() && $filter instanceof JsonSchemaFilterInterface && $schema = $filter->getSchema($parameter)) {
22✔
230
            $parameter = $parameter->withSchema($schema);
18✔
231
        }
232

233
        if (null === $parameter->getOpenApi() && $filter instanceof OpenApiParameterFilterInterface && ($openApiParameter = $filter->getOpenApiParameters($parameter))) {
22✔
234
            $parameter = $parameter->withOpenApi($openApiParameter);
12✔
235
        }
236

237
        return $parameter;
22✔
238
    }
239

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

249
        if ($filter instanceof SerializerFilterInterface && null === $parameter->getProvider()) {
36✔
250
            $parameter = $parameter->withProvider('api_platform.serializer.filter_parameter_provider');
2✔
251
        }
252

253
        $currentKey = $key;
36✔
254
        if (null === $parameter->getProperty() && isset($properties[$key])) {
36✔
255
            $parameter = $parameter->withProperty($key);
18✔
256
        }
257

258
        if ($this->nameConverter && $property = $parameter->getProperty()) {
36✔
259
            $parameter = $parameter->withProperty($this->nameConverter->normalize($property));
26✔
260
        }
261

262
        if (isset($properties[$currentKey]) && ($eloquentRelation = ($properties[$currentKey]->getExtraProperties()['eloquent_relation'] ?? null)) && isset($eloquentRelation['foreign_key'])) {
36✔
263
            $parameter = $parameter->withProperty($eloquentRelation['foreign_key']);
×
264
        }
265

266
        $parameter = $this->addFilterMetadata($parameter);
36✔
267

268
        if ($filter instanceof FilterInterface) {
36✔
269
            try {
270
                return $this->getLegacyFilterMetadata($parameter, $operation, $filter);
22✔
271
            } catch (RuntimeException $exception) {
12✔
272
                $this->logger?->alert($exception->getMessage(), ['exception' => $exception]);
12✔
273

274
                return $parameter;
12✔
275
            }
276
        }
277

278
        return $parameter;
18✔
279
    }
280

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

289
        if (null === $parameter->getProperty() && ($property = $description[$key]['property'] ?? null)) {
10✔
290
            $parameter = $parameter->withProperty($property);
×
291
        }
292

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

297
        if (null === $parameter->getOpenApi() && ($openApi = $description[$key]['openapi'] ?? null) && $openApi instanceof OpenApiParameter) {
10✔
298
            $parameter = $parameter->withOpenApi($openApi);
×
299
        }
300

301
        return $parameter;
10✔
302
    }
303

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

315
        if (\is_object($filter)) {
22✔
316
            return $filter;
20✔
317
        }
318

319
        if (!$this->filterLocator->has($filter)) {
6✔
320
            return null;
×
321
        }
322

323
        return $this->filterLocator->get($filter);
6✔
324
    }
325
}
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