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

api-platform / core / 13203378522

07 Feb 2025 03:56PM UTC coverage: 8.501% (+0.7%) from 7.837%
13203378522

push

github

soyuka
Merge 4.1

111 of 490 new or added lines in 51 files covered. (22.65%)

5590 existing lines in 163 files now uncovered.

13345 of 156987 relevant lines covered (8.5%)

22.88 hits per line

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

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

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

56
    public function create(string $resourceClass): ResourceMetadataCollection
57
    {
58
        $resourceMetadataCollection = $this->decorated?->create($resourceClass) ?? new ResourceMetadataCollection($resourceClass);
135✔
59

60
        foreach ($resourceMetadataCollection as $i => $resource) {
135✔
61
            $operations = $resource->getOperations();
128✔
62

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

71
            $resourceMetadataCollection[$i] = $resource->withOperations($operations->sort());
128✔
72

73
            if (!$graphQlOperations = $resource->getGraphQlOperations()) {
128✔
74
                continue;
56✔
75
            }
76

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

85
            $resourceMetadataCollection[$i] = $resource->withGraphQlOperations($graphQlOperations);
109✔
86
        }
87

88
        return $resourceMetadataCollection;
135✔
89
    }
90

91
    /**
92
     * @return array{propertyNames: string[], properties: array<string, ApiProperty>}
93
     */
94
    private function getProperties(string $resourceClass): array
95
    {
96
        if (isset($this->localPropertyCache[$resourceClass])) {
128✔
97
            return $this->localPropertyCache[$resourceClass];
111✔
98
        }
99

100
        $propertyNames = [];
128✔
101
        $properties = [];
128✔
102
        foreach ($this->propertyNameCollectionFactory->create($resourceClass) as $property) {
128✔
103
            $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $property);
118✔
104
            if ($propertyMetadata->isReadable()) {
118✔
105
                $propertyNames[] = $property;
118✔
106
                $properties[$property] = $propertyMetadata;
118✔
107
            }
108
        }
109

110
        $this->localPropertyCache = [$resourceClass => ['propertyNames' => $propertyNames, 'properties' => $properties]];
128✔
111

112
        return $this->localPropertyCache[$resourceClass];
128✔
113
    }
114

115
    private function getDefaultParameters(Operation $operation, string $resourceClass, int &$internalPriority): Parameters
116
    {
117
        ['propertyNames' => $propertyNames, 'properties' => $properties] = $this->getProperties($resourceClass);
128✔
118
        $parameters = $operation->getParameters() ?? new Parameters();
128✔
119
        foreach ($parameters as $key => $parameter) {
128✔
120
            if (':property' === $key) {
29✔
121
                foreach ($propertyNames as $property) {
4✔
122
                    $converted = $this->nameConverter?->denormalize($property) ?? $property;
4✔
123
                    $propertyParameter = $this->setDefaults($converted, $parameter, $resourceClass, $properties, $operation);
4✔
124
                    $priority = $propertyParameter->getPriority() ?? $internalPriority--;
4✔
125
                    $parameters->add($converted, $propertyParameter->withPriority($priority)->withKey($converted));
4✔
126
                }
127

128
                $parameters->remove($key, $parameter::class);
4✔
129
                continue;
4✔
130
            }
131

132
            $key = $parameter->getKey() ?? $key;
29✔
133

134
            if (str_contains($key, ':property') || (($f = $parameter->getFilter()) && is_a($f, PropertiesAwareInterface::class, true)) || $parameter instanceof PropertiesAwareInterface) {
29✔
135
                $p = [];
10✔
136
                foreach ($propertyNames as $prop) {
10✔
137
                    $p[$this->nameConverter?->denormalize($prop) ?? $prop] = $prop;
8✔
138
                }
139

140
                $parameter = $parameter->withExtraProperties($parameter->getExtraProperties() + ['_properties' => $p]);
10✔
141
            }
142

143
            $parameter = $this->setDefaults($key, $parameter, $resourceClass, $properties, $operation);
29✔
144
            $priority = $parameter->getPriority() ?? $internalPriority--;
29✔
145
            $parameters->add($key, $parameter->withPriority($priority));
29✔
146
        }
147

148
        return $parameters;
128✔
149
    }
150

151
    private function addFilterMetadata(Parameter $parameter): Parameter
152
    {
153
        if (!($filterId = $parameter->getFilter())) {
29✔
154
            return $parameter;
14✔
155
        }
156

157
        if (!\is_object($filterId) && !$this->filterLocator->has($filterId)) {
21✔
158
            return $parameter;
×
159
        }
160

161
        $filter = \is_object($filterId) ? $filterId : $this->filterLocator->get($filterId);
21✔
162

163
        if ($filter instanceof ParameterProviderFilterInterface) {
21✔
164
            $parameter = $parameter->withProvider($filter::getParameterProvider());
×
165
        }
166

167
        if (!$filter) {
21✔
168
            return $parameter;
×
169
        }
170

171
        if (null === $parameter->getSchema() && $filter instanceof JsonSchemaFilterInterface && $schema = $filter->getSchema($parameter)) {
21✔
172
            $parameter = $parameter->withSchema($schema);
19✔
173
        }
174

175
        if (null === $parameter->getOpenApi() && $filter instanceof OpenApiParameterFilterInterface && ($openApiParameter = $filter->getOpenApiParameters($parameter))) {
21✔
176
            $parameter = $parameter->withOpenApi($openApiParameter);
13✔
177
        }
178

179
        return $parameter;
21✔
180
    }
181

182
    /**
183
     * @param array<string, ApiProperty> $properties
184
     */
185
    private function setDefaults(string $key, Parameter $parameter, string $resourceClass, array $properties, Operation $operation): Parameter
186
    {
187
        if (null === $parameter->getKey()) {
29✔
188
            $parameter = $parameter->withKey($key);
29✔
189
        }
190

191
        $filter = $parameter->getFilter();
29✔
192
        if (\is_string($filter) && $this->filterLocator->has($filter)) {
29✔
193
            $filter = $this->filterLocator->get($filter);
9✔
194
        }
195

196
        if ($filter instanceof SerializerFilterInterface && null === $parameter->getProvider()) {
29✔
197
            $parameter = $parameter->withProvider('api_platform.serializer.filter_parameter_provider');
4✔
198
        }
199
        $currentKey = $key;
29✔
200
        if (null === $parameter->getProperty() && isset($properties[$key])) {
29✔
201
            $parameter = $parameter->withProperty($key);
19✔
202
        }
203

204
        if (null === $parameter->getProperty() && $this->nameConverter && ($nameConvertedKey = $this->nameConverter->normalize($key)) && isset($properties[$nameConvertedKey])) {
29✔
205
            $parameter = $parameter->withProperty($key)->withExtraProperties(['_query_property' => $nameConvertedKey] + $parameter->getExtraProperties());
×
206
            $currentKey = $nameConvertedKey;
×
207
        }
208

209
        if ($this->nameConverter && $property = $parameter->getProperty()) {
29✔
210
            $parameter = $parameter->withProperty($this->nameConverter->normalize($property));
21✔
211
        }
212

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

217
        $parameter = $this->addFilterMetadata($parameter);
29✔
218

219
        if ($filter instanceof FilterInterface) {
29✔
220
            try {
221
                return $this->getLegacyFilterMetadata($parameter, $operation, $filter);
21✔
222
            } catch (RuntimeException $exception) {
14✔
223
                $this->logger?->alert($exception->getMessage(), ['exception' => $exception]);
14✔
224

225
                return $parameter;
14✔
226
            }
227
        }
228

229
        return $parameter;
14✔
230
    }
231

232
    private function getLegacyFilterMetadata(Parameter $parameter, Operation $operation, FilterInterface $filter): Parameter
233
    {
234
        $description = $filter->getDescription($this->getFilterClass($operation));
21✔
235
        $key = $parameter->getKey();
9✔
236
        if (($schema = $description[$key]['schema'] ?? null) && null === $parameter->getSchema()) {
9✔
UNCOV
237
            $parameter = $parameter->withSchema($schema);
×
238
        }
239

240
        if (null === $parameter->getProperty() && ($property = $description[$key]['property'] ?? null)) {
9✔
UNCOV
241
            $parameter = $parameter->withProperty($property);
×
242
        }
243

244
        if (null === $parameter->getRequired() && ($required = $description[$key]['required'] ?? null)) {
9✔
UNCOV
245
            $parameter = $parameter->withRequired($required);
×
246
        }
247

248
        if (null === $parameter->getOpenApi() && ($openApi = $description[$key]['openapi'] ?? null) && $openApi instanceof OpenApiParameter) {
9✔
UNCOV
249
            $parameter = $parameter->withOpenApi($openApi);
×
250
        }
251

252
        return $parameter;
9✔
253
    }
254

255
    private function getFilterClass(Operation $operation): ?string
256
    {
257
        $stateOptions = $operation->getStateOptions();
21✔
258
        if ($stateOptions instanceof DoctrineORMOptions) {
21✔
259
            return $stateOptions->getEntityClass();
6✔
260
        }
261
        if ($stateOptions instanceof DoctrineODMOptions) {
21✔
262
            return $stateOptions->getDocumentClass();
4✔
263
        }
264

265
        return $operation->getClass();
18✔
266
    }
267
}
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