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

api-platform / core / 10814494863

11 Sep 2024 03:11PM UTC coverage: 7.008% (-0.7%) from 7.679%
10814494863

push

github

web-flow
fix(state): remove resource_class change (#6607)

11516 of 164321 relevant lines covered (7.01%)

22.85 hits per line

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

95.17
/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\FilterInterface;
18
use ApiPlatform\Metadata\HasOpenApiParameterFilterInterface;
19
use ApiPlatform\Metadata\HasSchemaFilterInterface;
20
use ApiPlatform\Metadata\HttpOperation;
21
use ApiPlatform\Metadata\Parameter;
22
use ApiPlatform\Metadata\Parameters;
23
use ApiPlatform\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
24
use ApiPlatform\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
25
use ApiPlatform\Metadata\QueryParameter;
26
use ApiPlatform\Metadata\Resource\ResourceMetadataCollection;
27
use ApiPlatform\OpenApi\Model\Parameter as OpenApiParameter;
28
use ApiPlatform\Serializer\Filter\FilterInterface as SerializerFilterInterface;
29
use Psr\Container\ContainerInterface;
30
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
31
use Symfony\Component\Validator\Constraints\Choice;
32
use Symfony\Component\Validator\Constraints\Count;
33
use Symfony\Component\Validator\Constraints\DivisibleBy;
34
use Symfony\Component\Validator\Constraints\GreaterThan;
35
use Symfony\Component\Validator\Constraints\GreaterThanOrEqual;
36
use Symfony\Component\Validator\Constraints\Length;
37
use Symfony\Component\Validator\Constraints\LessThan;
38
use Symfony\Component\Validator\Constraints\LessThanOrEqual;
39
use Symfony\Component\Validator\Constraints\NotBlank;
40
use Symfony\Component\Validator\Constraints\NotNull;
41
use Symfony\Component\Validator\Constraints\Regex;
42
use Symfony\Component\Validator\Constraints\Type;
43
use Symfony\Component\Validator\Constraints\Unique;
44
use Symfony\Component\Validator\Validator\ValidatorInterface;
45

46
/**
47
 * Prepares Parameters documentation by reading its filter details and declaring an OpenApi parameter.
48
 *
49
 * @experimental
50
 */
51
final class ParameterResourceMetadataCollectionFactory implements ResourceMetadataCollectionFactoryInterface
52
{
53
    public function __construct(
54
        private readonly PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory,
55
        private readonly PropertyMetadataFactoryInterface $propertyMetadataFactory,
56
        private readonly ?ResourceMetadataCollectionFactoryInterface $decorated = null,
57
        private readonly ?ContainerInterface $filterLocator = null,
58
        private readonly ?NameConverterInterface $nameConverter = null,
59
    ) {
60
    }
2,252✔
61

62
    public function create(string $resourceClass): ResourceMetadataCollection
63
    {
64
        $resourceMetadataCollection = $this->decorated?->create($resourceClass) ?? new ResourceMetadataCollection($resourceClass);
42✔
65

66
        $propertyNames = [];
42✔
67
        $properties = [];
42✔
68
        foreach ($this->propertyNameCollectionFactory->create($resourceClass) as $i => $property) {
42✔
69
            $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $property);
42✔
70
            if ('author' === $property) {
42✔
71
            }
72
            if ($propertyMetadata->isReadable()) {
42✔
73
                $propertyNames[] = $property;
42✔
74
                $properties[$property] = $propertyMetadata;
42✔
75
            }
76
        }
77

78
        foreach ($resourceMetadataCollection as $i => $resource) {
42✔
79
            $operations = $resource->getOperations();
34✔
80

81
            $internalPriority = -1;
34✔
82
            foreach ($operations as $operationName => $operation) {
34✔
83
                $parameters = $operation->getParameters() ?? new Parameters();
34✔
84
                foreach ($parameters as $key => $parameter) {
34✔
85
                    if (':property' === $key) {
3✔
86
                        foreach ($propertyNames as $property) {
3✔
87
                            $converted = $this->nameConverter?->denormalize($property) ?? $property;
3✔
88
                            $propertyParameter = $this->setDefaults($converted, $parameter, $resourceClass, $properties);
3✔
89
                            $priority = $propertyParameter->getPriority() ?? $internalPriority--;
3✔
90
                            $parameters->add($converted, $this->addFilterMetadata($propertyParameter->withPriority($priority)->withKey($converted)));
3✔
91
                        }
92

93
                        $parameters->remove($key, $parameter::class);
3✔
94
                        continue;
3✔
95
                    }
96

97
                    $key = $parameter->getKey() ?? $key;
3✔
98

99
                    if (str_contains($key, ':property')) {
3✔
100
                        $p = [];
3✔
101
                        foreach ($propertyNames as $prop) {
3✔
102
                            $p[$this->nameConverter?->denormalize($prop) ?? $prop] = $prop;
3✔
103
                        }
104

105
                        $parameter = $parameter->withExtraProperties(($parameter->getExtraProperties() ?? []) + ['_properties' => $p]);
3✔
106
                    }
107

108
                    $parameter = $this->setDefaults($key, $parameter, $resourceClass, $properties);
3✔
109
                    $priority = $parameter->getPriority() ?? $internalPriority--;
3✔
110
                    $parameters->add($key, $this->addFilterMetadata($parameter->withPriority($priority)));
3✔
111
                }
112

113
                // As we deprecate the parameter validator, we declare a parameter for each filter transfering validation to the new system
114
                if ($operation->getFilters() && 0 === $parameters->count()) {
34✔
115
                    $parameters = $this->addFilterValidation($operation);
15✔
116
                }
117

118
                if (\count($parameters) > 0) {
34✔
119
                    $operations->add($operationName, $operation->withParameters($parameters));
13✔
120
                }
121
            }
122

123
            $resourceMetadataCollection[$i] = $resource->withOperations($operations->sort());
34✔
124

125
            if (!$graphQlOperations = $resource->getGraphQlOperations()) {
34✔
126
                continue;
16✔
127
            }
128

129
            $internalPriority = -1;
31✔
130
            foreach ($graphQlOperations as $operationName => $operation) {
31✔
131
                $parameters = $operation->getParameters() ?? new Parameters();
31✔
132
                foreach ($operation->getParameters() ?? [] as $key => $parameter) {
31✔
133
                    $key = $parameter->getKey() ?? $key;
3✔
134
                    $parameter = $this->setDefaults($key, $parameter, $resourceClass, $properties);
3✔
135
                    $priority = $parameter->getPriority() ?? $internalPriority--;
3✔
136
                    $parameters->add($key, $parameter->withPriority($priority));
3✔
137
                }
138

139
                $graphQlOperations[$operationName] = $operation->withParameters($parameters);
31✔
140
            }
141

142
            $resourceMetadataCollection[$i] = $resource->withGraphQlOperations($graphQlOperations);
31✔
143
        }
144

145
        return $resourceMetadataCollection;
42✔
146
    }
147

148
    private function addFilterMetadata(Parameter $parameter): Parameter
149
    {
150
        if (!($filterId = $parameter->getFilter())) {
3✔
151
            return $parameter;
3✔
152
        }
153

154
        $filter = \is_object($filterId) ? $filterId : $this->filterLocator->get($filterId);
3✔
155

156
        if (!$filter) {
3✔
157
            return $parameter;
×
158
        }
159

160
        if (null === $parameter->getSchema() && $filter instanceof HasSchemaFilterInterface) {
3✔
161
            if ($schema = $filter->getSchema($parameter)) {
3✔
162
                $parameter = $parameter->withSchema($schema);
3✔
163
            }
164
        }
165

166
        if (null === $parameter->getOpenApi() && $filter instanceof HasOpenApiParameterFilterInterface) {
3✔
167
            if ($openApiParameter = $filter->getOpenApiParameter($parameter)) {
3✔
168
                $parameter = $parameter->withOpenApi($openApiParameter);
3✔
169
            }
170
        }
171

172
        return $parameter;
3✔
173
    }
174

175
    /**
176
     * @param array<string, ApiProperty> $properties
177
     */
178
    private function setDefaults(string $key, Parameter $parameter, string $resourceClass, array $properties): Parameter
179
    {
180
        if (null === $parameter->getKey()) {
3✔
181
            $parameter = $parameter->withKey($key);
3✔
182
        }
183

184
        $filter = $parameter->getFilter();
3✔
185
        if (\is_string($filter) && $this->filterLocator->has($filter)) {
3✔
186
            $filter = $this->filterLocator->get($filter);
3✔
187
        }
188

189
        if ($filter instanceof SerializerFilterInterface && null === $parameter->getProvider()) {
3✔
190
            $parameter = $parameter->withProvider('api_platform.serializer.filter_parameter_provider');
3✔
191
        }
192

193
        // Read filter description to populate the Parameter
194
        $description = $filter instanceof FilterInterface ? $filter->getDescription($resourceClass) : [];
3✔
195
        if (($schema = $description[$key]['schema'] ?? null) && null === $parameter->getSchema()) {
3✔
196
            $parameter = $parameter->withSchema($schema);
×
197
        }
198

199
        if (null === $parameter->getProperty() && ($property = $description[$key]['property'] ?? null)) {
3✔
200
            $parameter = $parameter->withProperty($property);
3✔
201
        }
202

203
        $currentKey = $key;
3✔
204
        if (null === $parameter->getProperty() && isset($properties[$key])) {
3✔
205
            $parameter = $parameter->withProperty($key);
3✔
206
        }
207

208
        if (null === $parameter->getProperty() && $this->nameConverter && ($nameConvertedKey = $this->nameConverter->normalize($key)) && isset($properties[$nameConvertedKey])) {
3✔
209
            $parameter = $parameter->withProperty($key)->withExtraProperties(['_query_property' => $nameConvertedKey] + $parameter->getExtraProperties());
×
210
            $currentKey = $nameConvertedKey;
×
211
        }
212

213
        if (isset($properties[$currentKey]) && ($eloquentRelation = ($properties[$currentKey]->getExtraProperties()['eloquent_relation'] ?? null)) && isset($eloquentRelation['foreign_key'])) {
3✔
214
            $parameter = $parameter->withExtraProperties(['_query_property' => $eloquentRelation['foreign_key']] + $parameter->getExtraProperties());
×
215
        }
216

217
        if (null === $parameter->getRequired() && ($required = $description[$key]['required'] ?? null)) {
3✔
218
            $parameter = $parameter->withRequired($required);
×
219
        }
220

221
        if (null === $parameter->getOpenApi() && ($openApi = $description[$key]['openapi'] ?? null) && $openApi instanceof OpenApiParameter) {
3✔
222
            $parameter = $parameter->withOpenApi($openApi);
×
223
        }
224

225
        $schema = $parameter->getSchema() ?? (($openApi = $parameter->getOpenApi()) ? $openApi->getSchema() : null);
3✔
226

227
        // Only add validation if the Symfony Validator is installed
228
        if (interface_exists(ValidatorInterface::class) && !$parameter->getConstraints()) {
3✔
229
            $parameter = $this->addSchemaValidation($parameter, $schema, $parameter->getRequired() ?? $description['required'] ?? false, $parameter->getOpenApi() ?: null);
3✔
230
        }
231

232
        return $parameter;
3✔
233
    }
234

235
    private function addSchemaValidation(Parameter $parameter, ?array $schema = null, bool $required = false, ?OpenApiParameter $openApi = null): Parameter
236
    {
237
        $assertions = [];
13✔
238

239
        if ($required && false !== ($allowEmptyValue = $openApi?->getAllowEmptyValue())) {
13✔
240
            $assertions[] = new NotNull(message: \sprintf('The parameter "%s" is required.', $parameter->getKey()));
4✔
241
        }
242

243
        if (false === ($allowEmptyValue ?? $openApi?->getAllowEmptyValue())) {
13✔
244
            $assertions[] = new NotBlank(allowNull: !$required);
8✔
245
        }
246

247
        if (isset($schema['exclusiveMinimum'])) {
13✔
248
            $assertions[] = new GreaterThan(value: $schema['exclusiveMinimum']);
4✔
249
        }
250

251
        if (isset($schema['exclusiveMaximum'])) {
13✔
252
            $assertions[] = new LessThan(value: $schema['exclusiveMaximum']);
4✔
253
        }
254

255
        if (isset($schema['minimum'])) {
13✔
256
            $assertions[] = new GreaterThanOrEqual(value: $schema['minimum']);
4✔
257
        }
258

259
        if (isset($schema['maximum'])) {
13✔
260
            $assertions[] = new LessThanOrEqual(value: $schema['maximum']);
4✔
261
        }
262

263
        if (isset($schema['pattern'])) {
13✔
264
            $assertions[] = new Regex($schema['pattern']);
4✔
265
        }
266

267
        if (isset($schema['maxLength']) || isset($schema['minLength'])) {
13✔
268
            $assertions[] = new Length(min: $schema['minLength'] ?? null, max: $schema['maxLength'] ?? null);
4✔
269
        }
270

271
        if (isset($schema['minItems']) || isset($schema['maxItems'])) {
13✔
272
            $assertions[] = new Count(min: $schema['minItems'] ?? null, max: $schema['maxItems'] ?? null);
4✔
273
        }
274

275
        if (isset($schema['multipleOf'])) {
13✔
276
            $assertions[] = new DivisibleBy(value: $schema['multipleOf']);
4✔
277
        }
278

279
        if ($schema['uniqueItems'] ?? false) {
13✔
280
            $assertions[] = new Unique();
4✔
281
        }
282

283
        if (isset($schema['enum'])) {
13✔
284
            $assertions[] = new Choice(choices: $schema['enum']);
6✔
285
        }
286

287
        if (isset($schema['type']) && 'array' === $schema['type']) {
13✔
288
            $assertions[] = new Type(type: 'array');
3✔
289
        }
290

291
        if (!$assertions) {
13✔
292
            return $parameter;
10✔
293
        }
294

295
        if (1 === \count($assertions)) {
9✔
296
            return $parameter->withConstraints($assertions[0]);
9✔
297
        }
298

299
        return $parameter->withConstraints($assertions);
3✔
300
    }
301

302
    private function addFilterValidation(HttpOperation $operation): Parameters
303
    {
304
        $parameters = new Parameters();
15✔
305
        $internalPriority = -1;
15✔
306

307
        foreach ($operation->getFilters() as $filter) {
15✔
308
            if (!$this->filterLocator->has($filter)) {
15✔
309
                continue;
2✔
310
            }
311

312
            $filter = $this->filterLocator->get($filter);
15✔
313
            foreach ($filter->getDescription($operation->getClass()) as $parameterName => $definition) {
15✔
314
                $key = $parameterName;
13✔
315
                $required = $definition['required'] ?? false;
13✔
316
                $schema = $definition['schema'] ?? null;
13✔
317

318
                $openApi = null;
13✔
319
                if (isset($definition['openapi']) && $definition['openapi'] instanceof OpenApiParameter) {
13✔
320
                    $openApi = $definition['openapi'];
7✔
321
                }
322

323
                // The query parameter validator forced this, lets maintain BC on filters
324
                if (true === $required && !$openApi) {
13✔
325
                    $openApi = new OpenApiParameter(name: $key, in: 'query', allowEmptyValue: false);
4✔
326
                }
327

328
                $parameters->add($key, $this->addSchemaValidation(
13✔
329
                    // we disable openapi and hydra on purpose as their docs comes from filters see the condition for addFilterValidation above
330
                    new QueryParameter(key: $key, property: $definition['property'] ?? null, priority: $internalPriority--, schema: $schema, openApi: false, hydra: false),
13✔
331
                    $schema,
13✔
332
                    $required,
13✔
333
                    $openApi
13✔
334
                ));
13✔
335
            }
336
        }
337

338
        return $parameters;
15✔
339
    }
340
}
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