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

api-platform / core / 10523796051

23 Aug 2024 10:00AM UTC coverage: 6.984% (-0.7%) from 7.707%
10523796051

push

github

dunglas
chore(laravel): remove duplicated ItemNormalizer definition

11317 of 162035 relevant lines covered (6.98%)

14.3 hits per line

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

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

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

52
    public function create(string $resourceClass): ResourceMetadataCollection
53
    {
54
        $resourceMetadataCollection = $this->decorated?->create($resourceClass) ?? new ResourceMetadataCollection($resourceClass);
42✔
55

56
        foreach ($resourceMetadataCollection as $i => $resource) {
42✔
57
            $operations = $resource->getOperations();
34✔
58

59
            $internalPriority = -1;
34✔
60
            foreach ($operations as $operationName => $operation) {
34✔
61
                $parameters = $operation->getParameters() ?? new Parameters();
34✔
62
                foreach ($parameters as $key => $parameter) {
34✔
63
                    if (':property' === $key) {
3✔
64
                        foreach ($this->propertyNameCollectionFactory->create($resourceClass) as $property) {
3✔
65
                            $parameter = $this->setDefaults($property, $parameter, $resourceClass);
3✔
66
                            $priority = $parameter->getPriority() ?? $internalPriority--;
3✔
67
                            $parameters->add($property, $parameter->withPriority($priority)->withProperty($property)->withKey($property));
3✔
68
                        }
69

70
                        $parameters->remove($key, $parameter::class);
3✔
71
                        continue;
3✔
72
                    }
73

74
                    $key = $parameter->getKey() ?? $key;
3✔
75
                    $parameter = $this->setDefaults($key, $parameter, $resourceClass);
3✔
76
                    $priority = $parameter->getPriority() ?? $internalPriority--;
3✔
77
                    $parameters->add($key, $parameter->withPriority($priority));
3✔
78
                }
79

80
                // As we deprecate the parameter validator, we declare a parameter for each filter transfering validation to the new system
81
                if ($operation->getFilters() && 0 === $parameters->count()) {
34✔
82
                    $parameters = $this->addFilterValidation($operation);
15✔
83
                }
84

85
                if (\count($parameters) > 0) {
34✔
86
                    $operations->add($operationName, $operation->withParameters($parameters));
13✔
87
                }
88
            }
89

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

92
            if (!$graphQlOperations = $resource->getGraphQlOperations()) {
34✔
93
                continue;
16✔
94
            }
95

96
            $internalPriority = -1;
31✔
97
            foreach ($graphQlOperations as $operationName => $operation) {
31✔
98
                $parameters = $operation->getParameters() ?? new Parameters();
31✔
99
                foreach ($operation->getParameters() ?? [] as $key => $parameter) {
31✔
100
                    $key = $parameter->getKey() ?? $key;
3✔
101
                    $parameter = $this->setDefaults($key, $parameter, $resourceClass);
3✔
102
                    $priority = $parameter->getPriority() ?? $internalPriority--;
3✔
103
                    $parameters->add($key, $parameter->withPriority($priority));
3✔
104
                }
105

106
                $graphQlOperations[$operationName] = $operation->withParameters($parameters);
31✔
107
            }
108

109
            $resourceMetadataCollection[$i] = $resource->withGraphQlOperations($graphQlOperations);
31✔
110
        }
111

112
        return $resourceMetadataCollection;
42✔
113
    }
114

115
    private function setDefaults(string $key, Parameter $parameter, string $resourceClass): Parameter
116
    {
117
        if (null === $parameter->getKey()) {
3✔
118
            $parameter = $parameter->withKey($key);
3✔
119
        }
120

121
        $filter = $parameter->getFilter();
3✔
122
        if (\is_string($filter) && $this->filterLocator->has($filter)) {
3✔
123
            $filter = $this->filterLocator->get($filter);
3✔
124
        }
125

126
        if ($filter instanceof SerializerFilterInterface && null === $parameter->getProvider()) {
3✔
127
            $parameter = $parameter->withProvider('api_platform.serializer.filter_parameter_provider');
3✔
128
        }
129

130
        // Read filter description to populate the Parameter
131
        $description = $filter instanceof FilterInterface ? $filter->getDescription($resourceClass) : [];
3✔
132
        if (($schema = $description[$key]['schema'] ?? null) && null === $parameter->getSchema()) {
3✔
133
            $parameter = $parameter->withSchema($schema);
×
134
        }
135

136
        if (null === $parameter->getProperty() && ($property = $description[$key]['property'] ?? null)) {
3✔
137
            $parameter = $parameter->withProperty($property);
3✔
138
        }
139

140
        if (null === $parameter->getRequired() && ($required = $description[$key]['required'] ?? null)) {
3✔
141
            $parameter = $parameter->withRequired($required);
×
142
        }
143

144
        if (null === $parameter->getOpenApi() && ($openApi = $description[$key]['openapi'] ?? null) && $openApi instanceof OpenApiParameter) {
3✔
145
            $parameter = $parameter->withOpenApi($openApi);
×
146
        }
147

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

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

155
        return $parameter;
3✔
156
    }
157

158
    private function addSchemaValidation(Parameter $parameter, ?array $schema = null, bool $required = false, ?OpenApiParameter $openApi = null): Parameter
159
    {
160
        $assertions = [];
13✔
161

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

166
        if (false === ($allowEmptyValue ?? $openApi?->getAllowEmptyValue())) {
13✔
167
            $assertions[] = new NotBlank(allowNull: !$required);
8✔
168
        }
169

170
        if (isset($schema['exclusiveMinimum'])) {
13✔
171
            $assertions[] = new GreaterThan(value: $schema['exclusiveMinimum']);
4✔
172
        }
173

174
        if (isset($schema['exclusiveMaximum'])) {
13✔
175
            $assertions[] = new LessThan(value: $schema['exclusiveMaximum']);
4✔
176
        }
177

178
        if (isset($schema['minimum'])) {
13✔
179
            $assertions[] = new GreaterThanOrEqual(value: $schema['minimum']);
4✔
180
        }
181

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

186
        if (isset($schema['pattern'])) {
13✔
187
            $assertions[] = new Regex($schema['pattern']);
4✔
188
        }
189

190
        if (isset($schema['maxLength']) || isset($schema['minLength'])) {
13✔
191
            $assertions[] = new Length(min: $schema['minLength'] ?? null, max: $schema['maxLength'] ?? null);
4✔
192
        }
193

194
        if (isset($schema['minItems']) || isset($schema['maxItems'])) {
13✔
195
            $assertions[] = new Count(min: $schema['minItems'] ?? null, max: $schema['maxItems'] ?? null);
4✔
196
        }
197

198
        if (isset($schema['multipleOf'])) {
13✔
199
            $assertions[] = new DivisibleBy(value: $schema['multipleOf']);
4✔
200
        }
201

202
        if ($schema['uniqueItems'] ?? false) {
13✔
203
            $assertions[] = new Unique();
4✔
204
        }
205

206
        if (isset($schema['enum'])) {
13✔
207
            $assertions[] = new Choice(choices: $schema['enum']);
6✔
208
        }
209

210
        if (isset($schema['type']) && 'array' === $schema['type']) {
13✔
211
            $assertions[] = new Type(type: 'array');
3✔
212
        }
213

214
        if (!$assertions) {
13✔
215
            return $parameter;
10✔
216
        }
217

218
        if (1 === \count($assertions)) {
9✔
219
            return $parameter->withConstraints($assertions[0]);
9✔
220
        }
221

222
        return $parameter->withConstraints($assertions);
3✔
223
    }
224

225
    private function addFilterValidation(HttpOperation $operation): Parameters
226
    {
227
        $parameters = new Parameters();
15✔
228
        $internalPriority = -1;
15✔
229

230
        foreach ($operation->getFilters() as $filter) {
15✔
231
            if (!$this->filterLocator->has($filter)) {
15✔
232
                continue;
2✔
233
            }
234

235
            $filter = $this->filterLocator->get($filter);
15✔
236
            foreach ($filter->getDescription($operation->getClass()) as $parameterName => $definition) {
15✔
237
                $key = $parameterName;
13✔
238
                $required = $definition['required'] ?? false;
13✔
239
                $schema = $definition['schema'] ?? null;
13✔
240

241
                $openApi = null;
13✔
242
                if (isset($definition['openapi']) && $definition['openapi'] instanceof OpenApiParameter) {
13✔
243
                    $openApi = $definition['openapi'];
7✔
244
                }
245

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

251
                $parameters->add($key, $this->addSchemaValidation(
13✔
252
                    // we disable openapi and hydra on purpose as their docs comes from filters see the condition for addFilterValidation above
253
                    new QueryParameter(key: $key, property: $definition['property'] ?? null, priority: $internalPriority--, schema: $schema, openApi: false, hydra: false),
13✔
254
                    $schema,
13✔
255
                    $required,
13✔
256
                    $openApi
13✔
257
                ));
13✔
258
            }
259
        }
260

261
        return $parameters;
15✔
262
    }
263
}
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