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

api-platform / core / 15133993414

20 May 2025 09:30AM UTC coverage: 26.313% (-1.2%) from 27.493%
15133993414

Pull #7161

github

web-flow
Merge e2c03d45f into 5459ba375
Pull Request #7161: fix(metadata): infer parameter string type from schema

0 of 2 new or added lines in 1 file covered. (0.0%)

11019 existing lines in 363 files now uncovered.

12898 of 49018 relevant lines covered (26.31%)

34.33 hits per line

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

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

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

46
    private array $localPropertyCache;
47

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

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

UNCOV
62
        foreach ($resourceMetadataCollection as $i => $resource) {
69✔
UNCOV
63
            $operations = $resource->getOperations();
65✔
64

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

UNCOV
73
            $resourceMetadataCollection[$i] = $resource->withOperations($operations->sort());
65✔
74

UNCOV
75
            if (!$graphQlOperations = $resource->getGraphQlOperations()) {
65✔
UNCOV
76
                continue;
29✔
77
            }
78

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

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

UNCOV
90
        return $resourceMetadataCollection;
69✔
91
    }
92

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

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

UNCOV
113
        $this->localPropertyCache[$k] = ['propertyNames' => $propertyNames, 'properties' => $properties];
15✔
114

UNCOV
115
        return $this->localPropertyCache[$k];
15✔
116
    }
117

118
    private function getDefaultParameters(Operation $operation, string $resourceClass, int &$internalPriority): Parameters
119
    {
UNCOV
120
        $propertyNames = $properties = [];
65✔
UNCOV
121
        $parameters = $operation->getParameters() ?? new Parameters();
65✔
UNCOV
122
        foreach ($parameters as $key => $parameter) {
65✔
UNCOV
123
            ['propertyNames' => $propertyNames, 'properties' => $properties] = $this->getProperties($resourceClass, $parameter);
15✔
UNCOV
124
            if (null === $parameter->getProvider() && (($f = $parameter->getFilter()) && $f instanceof ParameterProviderFilterInterface)) {
15✔
125
                $parameters->add($key, $parameter->withProvider($f->getParameterProvider()));
×
126
            }
127

UNCOV
128
            if (':property' === $key) {
15✔
UNCOV
129
                foreach ($propertyNames as $property) {
2✔
UNCOV
130
                    $converted = $this->nameConverter?->denormalize($property) ?? $property;
2✔
UNCOV
131
                    $propertyParameter = $this->setDefaults($converted, $parameter, $resourceClass, $properties, $operation);
2✔
UNCOV
132
                    $priority = $propertyParameter->getPriority() ?? $internalPriority--;
2✔
UNCOV
133
                    $parameters->add($converted, $propertyParameter->withPriority($priority)->withKey($converted));
2✔
134
                }
135

UNCOV
136
                $parameters->remove($key, $parameter::class);
2✔
UNCOV
137
                continue;
2✔
138
            }
139

UNCOV
140
            $key = $parameter->getKey() ?? $key;
15✔
141

UNCOV
142
            if (str_contains($key, ':property') || ((($f = $parameter->getFilter()) && is_a($f, PropertiesAwareInterface::class, true)) || $parameter instanceof PropertiesAwareInterface)) {
15✔
UNCOV
143
                $p = [];
6✔
UNCOV
144
                foreach ($propertyNames as $prop) {
6✔
UNCOV
145
                    $p[$this->nameConverter?->denormalize($prop) ?? $prop] = $prop;
5✔
146
                }
147

UNCOV
148
                $parameter = $parameter->withExtraProperties($parameter->getExtraProperties() + ['_properties' => $p]);
6✔
149
            }
150

UNCOV
151
            $parameter = $this->setDefaults($key, $parameter, $resourceClass, $properties, $operation);
15✔
152
            // We don't do any type cast yet, a query parameter or an header is always a string or a list of strings
UNCOV
153
            if (null === $parameter->getNativeType()) {
15✔
154
                // this forces the type to be only a list
UNCOV
155
                if ('array' === ($parameter->getSchema()['type'] ?? null)) {
13✔
UNCOV
156
                    $parameter = $parameter->withNativeType(Type::list(Type::string()));
2✔
NEW
157
                } elseif ('string' === ($parameter->getSchema()['type'] ?? null)) {
13✔
NEW
158
                    $parameter = $parameter->withNativeType(Type::string());
7✔
159
                } else {
UNCOV
160
                    $parameter = $parameter->withNativeType(Type::union(Type::string(), Type::list(Type::string())));
9✔
161
                }
162
            }
163

UNCOV
164
            $priority = $parameter->getPriority() ?? $internalPriority--;
15✔
UNCOV
165
            $parameters->add($key, $parameter->withPriority($priority));
15✔
166
        }
167

UNCOV
168
        return $parameters;
65✔
169
    }
170

171
    private function addFilterMetadata(Parameter $parameter): Parameter
172
    {
UNCOV
173
        if (!($filterId = $parameter->getFilter())) {
15✔
UNCOV
174
            return $parameter;
7✔
175
        }
176

UNCOV
177
        if (!\is_object($filterId) && !$this->filterLocator->has($filterId)) {
11✔
178
            return $parameter;
×
179
        }
180

UNCOV
181
        $filter = \is_object($filterId) ? $filterId : $this->filterLocator->get($filterId);
11✔
182

UNCOV
183
        if ($filter instanceof ParameterProviderFilterInterface) {
11✔
184
            $parameter = $parameter->withProvider($filter::getParameterProvider());
×
185
        }
186

UNCOV
187
        if (!$filter) {
11✔
188
            return $parameter;
×
189
        }
190

UNCOV
191
        if (null === $parameter->getSchema() && $filter instanceof JsonSchemaFilterInterface && $schema = $filter->getSchema($parameter)) {
11✔
UNCOV
192
            $parameter = $parameter->withSchema($schema);
10✔
193
        }
194

UNCOV
195
        if (null === $parameter->getOpenApi() && $filter instanceof OpenApiParameterFilterInterface && ($openApiParameter = $filter->getOpenApiParameters($parameter))) {
11✔
UNCOV
196
            $parameter = $parameter->withOpenApi($openApiParameter);
6✔
197
        }
198

UNCOV
199
        return $parameter;
11✔
200
    }
201

202
    /**
203
     * @param array<string, ApiProperty> $properties
204
     */
205
    private function setDefaults(string $key, Parameter $parameter, string $resourceClass, array $properties, Operation $operation): Parameter
206
    {
UNCOV
207
        if (null === $parameter->getKey()) {
15✔
UNCOV
208
            $parameter = $parameter->withKey($key);
15✔
209
        }
210

UNCOV
211
        $filter = $parameter->getFilter();
15✔
UNCOV
212
        if (\is_string($filter) && $this->filterLocator->has($filter)) {
15✔
UNCOV
213
            $filter = $this->filterLocator->get($filter);
4✔
214
        }
215

UNCOV
216
        if ($filter instanceof SerializerFilterInterface && null === $parameter->getProvider()) {
15✔
UNCOV
217
            $parameter = $parameter->withProvider('api_platform.serializer.filter_parameter_provider');
2✔
218
        }
UNCOV
219
        $currentKey = $key;
15✔
UNCOV
220
        if (null === $parameter->getProperty() && isset($properties[$key])) {
15✔
UNCOV
221
            $parameter = $parameter->withProperty($key);
9✔
222
        }
223

UNCOV
224
        if (null === $parameter->getProperty() && $this->nameConverter && ($nameConvertedKey = $this->nameConverter->normalize($key)) && isset($properties[$nameConvertedKey])) {
15✔
225
            $parameter = $parameter->withProperty($key)->withExtraProperties(['_query_property' => $nameConvertedKey] + $parameter->getExtraProperties());
×
226
            $currentKey = $nameConvertedKey;
×
227
        }
228

UNCOV
229
        if ($this->nameConverter && $property = $parameter->getProperty()) {
15✔
UNCOV
230
            $parameter = $parameter->withProperty($this->nameConverter->normalize($property));
11✔
231
        }
232

UNCOV
233
        if (isset($properties[$currentKey]) && ($eloquentRelation = ($properties[$currentKey]->getExtraProperties()['eloquent_relation'] ?? null)) && isset($eloquentRelation['foreign_key'])) {
15✔
234
            $parameter = $parameter->withExtraProperties(['_query_property' => $eloquentRelation['foreign_key']] + $parameter->getExtraProperties());
×
235
        }
236

UNCOV
237
        $parameter = $this->addFilterMetadata($parameter);
15✔
238

UNCOV
239
        if ($filter instanceof FilterInterface) {
15✔
240
            try {
UNCOV
241
                return $this->getLegacyFilterMetadata($parameter, $operation, $filter);
11✔
UNCOV
242
            } catch (RuntimeException $exception) {
7✔
UNCOV
243
                $this->logger?->alert($exception->getMessage(), ['exception' => $exception]);
7✔
244

UNCOV
245
                return $parameter;
7✔
246
            }
247
        }
248

UNCOV
249
        return $parameter;
7✔
250
    }
251

252
    private function getLegacyFilterMetadata(Parameter $parameter, Operation $operation, FilterInterface $filter): Parameter
253
    {
UNCOV
254
        $description = $filter->getDescription($this->getStateOptionsClass($operation, $operation->getClass()));
11✔
UNCOV
255
        $key = $parameter->getKey();
5✔
UNCOV
256
        if (($schema = $description[$key]['schema'] ?? null) && null === $parameter->getSchema()) {
5✔
257
            $parameter = $parameter->withSchema($schema);
×
258
        }
259

UNCOV
260
        if (null === $parameter->getProperty() && ($property = $description[$key]['property'] ?? null)) {
5✔
261
            $parameter = $parameter->withProperty($property);
×
262
        }
263

UNCOV
264
        if (null === $parameter->getRequired() && ($required = $description[$key]['required'] ?? null)) {
5✔
265
            $parameter = $parameter->withRequired($required);
×
266
        }
267

UNCOV
268
        if (null === $parameter->getOpenApi() && ($openApi = $description[$key]['openapi'] ?? null) && $openApi instanceof OpenApiParameter) {
5✔
269
            $parameter = $parameter->withOpenApi($openApi);
×
270
        }
271

UNCOV
272
        return $parameter;
5✔
273
    }
274
}
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