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

api-platform / core / 11515845204

25 Oct 2024 09:44AM UTC coverage: 62.1% (+0.1%) from 61.98%
11515845204

push

github

web-flow
fix(hydra): iri template when using query parameter (#6742)

62 of 64 new or added lines in 2 files covered. (96.88%)

7 existing lines in 3 files now uncovered.

11450 of 18438 relevant lines covered (62.1%)

67.93 hits per line

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

96.77
/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\Odm\State\Options as DoctrineOdmOptions;
17
use ApiPlatform\Doctrine\Orm\State\Options as DoctrineOrmOptions;
18
use ApiPlatform\Metadata\FilterInterface;
19
use ApiPlatform\Metadata\HttpOperation;
20
use ApiPlatform\Metadata\Operation;
21
use ApiPlatform\Metadata\Parameter;
22
use ApiPlatform\Metadata\Parameters;
23
use ApiPlatform\Metadata\QueryParameter;
24
use ApiPlatform\Metadata\Resource\ResourceMetadataCollection;
25
use ApiPlatform\OpenApi\Model\Parameter as OpenApiParameter;
26
use ApiPlatform\Serializer\Filter\FilterInterface as SerializerFilterInterface;
27
use Psr\Container\ContainerInterface;
28
use Symfony\Component\Validator\Constraints\Choice;
29
use Symfony\Component\Validator\Constraints\Count;
30
use Symfony\Component\Validator\Constraints\DivisibleBy;
31
use Symfony\Component\Validator\Constraints\GreaterThan;
32
use Symfony\Component\Validator\Constraints\GreaterThanOrEqual;
33
use Symfony\Component\Validator\Constraints\Length;
34
use Symfony\Component\Validator\Constraints\LessThan;
35
use Symfony\Component\Validator\Constraints\LessThanOrEqual;
36
use Symfony\Component\Validator\Constraints\NotBlank;
37
use Symfony\Component\Validator\Constraints\NotNull;
38
use Symfony\Component\Validator\Constraints\Regex;
39
use Symfony\Component\Validator\Constraints\Type;
40
use Symfony\Component\Validator\Constraints\Unique;
41
use Symfony\Component\Validator\Validator\ValidatorInterface;
42

43
/**
44
 * Prepares Parameters documentation by reading its filter details and declaring an OpenApi parameter.
45
 *
46
 * @experimental
47
 */
48
final class ParameterResourceMetadataCollectionFactory implements ResourceMetadataCollectionFactoryInterface
49
{
50
    public function __construct(private readonly ?ResourceMetadataCollectionFactoryInterface $decorated = null, private readonly ?ContainerInterface $filterLocator = null)
51
    {
52
    }
583✔
53

54
    public function create(string $resourceClass): ResourceMetadataCollection
55
    {
56
        $resourceMetadataCollection = $this->decorated?->create($resourceClass) ?? new ResourceMetadataCollection($resourceClass);
12✔
57

58
        foreach ($resourceMetadataCollection as $i => $resource) {
12✔
59
            $resourceClass = $resource->getClass();
12✔
60
            $operations = $resource->getOperations();
12✔
61

62
            $internalPriority = -1;
12✔
63
            foreach ($operations as $operationName => $operation) {
12✔
64
                $parameters = $operation->getParameters() ?? new Parameters();
12✔
65
                foreach ($parameters as $key => $parameter) {
12✔
66
                    $key = $parameter->getKey() ?? $key;
4✔
67
                    $parameter = $this->setDefaults($key, $parameter, $resourceClass, $operation);
4✔
68
                    $priority = $parameter->getPriority() ?? $internalPriority--;
4✔
69
                    $parameters->add($key, $parameter->withPriority($priority));
4✔
70
                }
71

72
                // As we deprecate the parameter validator, we declare a parameter for each filter transfering validation to the new system
73
                if ($operation->getFilters() && 0 === $parameters->count() && false === ($operation->getExtraProperties()['use_legacy_parameter_validator'] ?? true)) {
12✔
74
                    $parameters = $this->addFilterValidation($operation);
4✔
75
                }
76

77
                if (\count($parameters) > 0) {
12✔
78
                    $operations->add($operationName, $operation->withParameters($parameters));
4✔
79
                }
80
            }
81

82
            $resourceMetadataCollection[$i] = $resource->withOperations($operations->sort());
12✔
83

84
            if (!$graphQlOperations = $resource->getGraphQlOperations()) {
12✔
85
                continue;
8✔
86
            }
87

88
            $internalPriority = -1;
8✔
89
            foreach ($graphQlOperations as $operationName => $operation) {
8✔
90
                $parameters = $operation->getParameters() ?? new Parameters();
8✔
91
                foreach ($operation->getParameters() ?? [] as $key => $parameter) {
8✔
92
                    $key = $parameter->getKey() ?? $key;
4✔
93
                    $parameter = $this->setDefaults($key, $parameter, $resourceClass, $operation);
4✔
94
                    $priority = $parameter->getPriority() ?? $internalPriority--;
4✔
95
                    $parameters->add($key, $parameter->withPriority($priority));
4✔
96
                }
97

98
                $graphQlOperations[$operationName] = $operation->withParameters($parameters);
8✔
99
            }
100

101
            $resourceMetadataCollection[$i] = $resource->withGraphQlOperations($graphQlOperations);
8✔
102
        }
103

104
        return $resourceMetadataCollection;
12✔
105
    }
106

107
    private function setDefaults(string $key, Parameter $parameter, string $resourceClass, Operation $operation): Parameter
108
    {
109
        if (null === $parameter->getKey()) {
4✔
110
            $parameter = $parameter->withKey($key);
4✔
111
        }
112

113
        $filter = $parameter->getFilter();
4✔
114
        if (\is_string($filter) && $this->filterLocator->has($filter)) {
4✔
115
            $filter = $this->filterLocator->get($filter);
4✔
116
        }
117

118
        if ($filter instanceof SerializerFilterInterface && null === $parameter->getProvider()) {
4✔
119
            $parameter = $parameter->withProvider('api_platform.serializer.filter_parameter_provider');
4✔
120
        }
121

122
        // Read filter description to populate the Parameter
123
        $description = $filter instanceof FilterInterface ? $filter->getDescription($this->getFilterClass($operation)) : [];
4✔
124
        if (($schema = $description[$key]['schema'] ?? null) && null === $parameter->getSchema()) {
4✔
125
            $parameter = $parameter->withSchema($schema);
×
126
        }
127

128
        if (null === $parameter->getRequired() && ($required = $description[$key]['required'] ?? null)) {
4✔
UNCOV
129
            $parameter = $parameter->withRequired($required);
×
130
        }
131

132
        $schema = $parameter->getSchema() ?? (($openApi = $parameter->getOpenApi()) ? $openApi->getSchema() : null);
4✔
133

134
        // Only add validation if the Symfony Validator is installed
135
        if (interface_exists(ValidatorInterface::class) && !$parameter->getConstraints()) {
4✔
136
            $parameter = $this->addSchemaValidation($parameter, $schema, $parameter->getRequired() ?? $description['required'] ?? false, $parameter->getOpenApi() ?: null);
4✔
137
        }
138

139
        return $parameter;
4✔
140
    }
141

142
    private function addSchemaValidation(Parameter $parameter, ?array $schema = null, bool $required = false, ?OpenApiParameter $openApi = null): Parameter
143
    {
144
        $assertions = [];
4✔
145

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

150
        if (false === ($allowEmptyValue ?? $openApi?->getAllowEmptyValue())) {
4✔
151
            $assertions[] = new NotBlank(allowNull: !$required);
4✔
152
        }
153

154
        if (isset($schema['exclusiveMinimum'])) {
4✔
155
            $assertions[] = new GreaterThan(value: $schema['exclusiveMinimum']);
4✔
156
        }
157

158
        if (isset($schema['exclusiveMaximum'])) {
4✔
159
            $assertions[] = new LessThan(value: $schema['exclusiveMaximum']);
4✔
160
        }
161

162
        if (isset($schema['minimum'])) {
4✔
163
            $assertions[] = new GreaterThanOrEqual(value: $schema['minimum']);
4✔
164
        }
165

166
        if (isset($schema['maximum'])) {
4✔
167
            $assertions[] = new LessThanOrEqual(value: $schema['maximum']);
4✔
168
        }
169

170
        if (isset($schema['pattern'])) {
4✔
171
            $assertions[] = new Regex($schema['pattern']);
4✔
172
        }
173

174
        if (isset($schema['maxLength']) || isset($schema['minLength'])) {
4✔
175
            $assertions[] = new Length(min: $schema['minLength'] ?? null, max: $schema['maxLength'] ?? null);
4✔
176
        }
177

178
        if (isset($schema['minItems']) || isset($schema['maxItems'])) {
4✔
179
            $assertions[] = new Count(min: $schema['minItems'] ?? null, max: $schema['maxItems'] ?? null);
4✔
180
        }
181

182
        if (isset($schema['multipleOf'])) {
4✔
183
            $assertions[] = new DivisibleBy(value: $schema['multipleOf']);
4✔
184
        }
185

186
        if ($schema['uniqueItems'] ?? false) {
4✔
187
            $assertions[] = new Unique();
4✔
188
        }
189

190
        if (isset($schema['enum'])) {
4✔
191
            $assertions[] = new Choice(choices: $schema['enum']);
4✔
192
        }
193

194
        if (isset($schema['type']) && 'array' === $schema['type']) {
4✔
195
            $assertions[] = new Type(type: 'array');
4✔
196
        }
197

198
        if (!$assertions) {
4✔
199
            return $parameter;
4✔
200
        }
201

202
        if (1 === \count($assertions)) {
4✔
203
            return $parameter->withConstraints($assertions[0]);
4✔
204
        }
205

206
        return $parameter->withConstraints($assertions);
4✔
207
    }
208

209
    private function addFilterValidation(HttpOperation $operation): Parameters
210
    {
211
        $parameters = new Parameters();
4✔
212
        $internalPriority = -1;
4✔
213

214
        foreach ($operation->getFilters() as $filter) {
4✔
215
            if (!$this->filterLocator->has($filter)) {
4✔
216
                continue;
×
217
            }
218

219
            $filter = $this->filterLocator->get($filter);
4✔
220
            foreach ($filter->getDescription($this->getFilterClass($operation)) as $parameterName => $definition) {
4✔
221
                $key = $parameterName;
4✔
222
                $required = $definition['required'] ?? false;
4✔
223
                $schema = $definition['schema'] ?? null;
4✔
224

225
                if (isset($definition['swagger'])) {
4✔
226
                    trigger_deprecation('api-platform/core', '3.4', 'The key "swagger" in a filter description is deprecated, use "schema" or "openapi" instead.');
4✔
227
                    $schema = $schema ?? $definition['swagger'];
4✔
228
                }
229

230
                $openApi = null;
4✔
231
                if (isset($definition['openapi'])) {
4✔
232
                    trigger_deprecation('api-platform/core', '3.4', \sprintf('The key "openapi" in a filter description should be a "%s" class or use "schema" to specify the JSON Schema.', OpenApiParameter::class));
4✔
233
                    if ($definition['openapi'] instanceof OpenApiParameter) {
4✔
234
                        $openApi = $definition['openapi'];
×
235
                    } else {
236
                        $schema = $schema ?? $openApi;
4✔
237
                    }
238
                }
239

240
                if (isset($schema['allowEmptyValue']) && !$openApi) {
4✔
241
                    trigger_deprecation('api-platform/core', '3.4', 'The "allowEmptyValue" option should be declared using an "openapi" parameter.');
4✔
242
                    $openApi = new OpenApiParameter(name: $key, in: 'query', allowEmptyValue: $schema['allowEmptyValue']);
4✔
243
                }
244

245
                // The query parameter validator forced this, lets maintain BC on filters
246
                if (true === $required && !$openApi) {
4✔
247
                    $openApi = new OpenApiParameter(name: $key, in: 'query', allowEmptyValue: false);
4✔
248
                }
249

250
                if (\is_bool($schema['exclusiveMinimum'] ?? null)) {
4✔
251
                    trigger_deprecation('api-platform/core', '3.4', 'The "exclusiveMinimum" schema value should be a number not a boolean.');
4✔
252
                    $schema['exclusiveMinimum'] = $schema['minimum'];
4✔
253
                    unset($schema['minimum']);
4✔
254
                }
255

256
                if (\is_bool($schema['exclusiveMaximum'] ?? null)) {
4✔
257
                    trigger_deprecation('api-platform/core', '3.4', 'The "exclusiveMaximum" schema value should be a number not a boolean.');
4✔
258
                    $schema['exclusiveMaximum'] = $schema['maximum'];
4✔
259
                    unset($schema['maximum']);
4✔
260
                }
261

262
                $parameters->add($key, $this->addSchemaValidation(
4✔
263
                    // we disable openapi and hydra on purpose as their docs comes from filters see the condition for addFilterValidation above
264
                    new QueryParameter(key: $key, property: $definition['property'] ?? null, priority: $internalPriority--, schema: $schema, openApi: false, hydra: false),
4✔
265
                    $schema,
4✔
266
                    $required,
4✔
267
                    $openApi
4✔
268
                ));
4✔
269
            }
270
        }
271

272
        return $parameters;
4✔
273
    }
274

275
    private function getFilterClass(Operation $operation): ?string
276
    {
277
        $stateOptions = $operation->getStateOptions();
4✔
278

279
        if ($stateOptions instanceof DoctrineOrmOptions) {
4✔
280
            return $stateOptions->getEntityClass();
4✔
281
        }
282

283
        if ($stateOptions instanceof DoctrineOdmOptions) {
4✔
284
            return $stateOptions->getDocumentClass();
4✔
285
        }
286

287
        return $operation->getClass();
4✔
288
    }
289
}
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