forked from api-platform/schema-generator
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApiPlatformCoreAttributeGenerator.php
More file actions
263 lines (239 loc) · 9.18 KB
/
ApiPlatformCoreAttributeGenerator.php
File metadata and controls
263 lines (239 loc) · 9.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
<?php
/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace ApiPlatform\SchemaGenerator\AttributeGenerator;
use ApiPlatform\Core\Annotation\ApiProperty as OldApiProperty;
use ApiPlatform\Core\Annotation\ApiResource as OldApiResource;
use ApiPlatform\Metadata\ApiProperty;
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Delete;
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\GetCollection;
use ApiPlatform\Metadata\Patch;
use ApiPlatform\Metadata\Post;
use ApiPlatform\Metadata\Put;
use ApiPlatform\OpenApi\Model\Operation;
use ApiPlatform\OpenApi\Model\Parameter;
use ApiPlatform\OpenApi\Model\Response;
use ApiPlatform\SchemaGenerator\Model\Attribute;
use ApiPlatform\SchemaGenerator\Model\Class_;
use ApiPlatform\SchemaGenerator\Model\Property;
use ApiPlatform\SchemaGenerator\Model\Use_;
use Nette\PhpGenerator\Literal;
use Symfony\Component\OptionsResolver\OptionsResolver;
/**
* Generates API Platform core attributes.
*
* @author Kévin Dunglas <dunglas@gmail.com>
*
* @see https://github.com/api-platform/core
*/
final class ApiPlatformCoreAttributeGenerator extends AbstractAttributeGenerator
{
/**
* Hints for not typed array parameters.
*/
private const PRAMETER_TYPE_HINTS = [
Operation::class => [
'responses' => Response::class.'[]',
'parameters' => Parameter::class.'[]',
],
];
/**
* @var array<class-string, array<string, string|null>>
*/
private static array $parameterTypes = [];
public function generateClassAttributes(Class_ $class): array
{
if ($class->hasChild || $class->isEnum()) {
return [];
}
$arguments = [];
if ($class->name() !== $localName = $class->shortName()) {
$arguments['shortName'] = $localName;
}
if ($class->rdfType()) {
if ($this->config['apiPlatformOldAttributes']) {
$arguments['iri'] = $class->rdfType();
} else {
$arguments['types'] = [$class->rdfType()];
}
}
if ($class->operations) {
if ($this->config['apiPlatformOldAttributes']) {
$operations = $this->validateClassOperations($class->operations);
foreach ($operations as $operationTarget => $targetOperations) {
$targetArguments = [];
foreach ($targetOperations ?? [] as $method => $methodConfig) {
$methodArguments = [];
if (!is_iterable($methodConfig)) {
continue;
}
foreach ($methodConfig as $key => $value) {
$methodArguments[$key] = $value;
}
$targetArguments[$method] = $methodArguments;
}
$arguments[\sprintf('%sOperations', $operationTarget)] = $targetArguments;
}
} else {
$arguments['operations'] = [];
foreach ($class->operations as $operationMetadataClass => $methodConfig) {
// https://github.com/api-platform/schema-generator/issues/405
if (\array_key_exists('class', $methodConfig ?? [])) {
/** @var string $operationMetadataClass */
$operationMetadataClass = $methodConfig['class'];
unset($methodConfig['class']);
}
if (\is_array($methodConfig['openapi'] ?? null)) {
$methodConfig['openapi'] = Literal::new(
'Operation',
self::extractParameters(Operation::class, $methodConfig['openapi'])
);
$class->addUse(new Use_(Operation::class));
array_walk_recursive(
self::$parameterTypes,
static function (?string $type) use ($class): void {
if (null !== $type) {
$class->addUse(new Use_(str_replace('[]', '', $type)));
}
}
);
}
$arguments['operations'][] = new Literal(\sprintf('new %s(...?:)',
$operationMetadataClass,
), [$methodConfig ?? []]);
}
}
}
return [new Attribute('ApiResource', $arguments)];
}
/**
* @param class-string $type
* @param mixed[] $values
*
* @return mixed[]
*/
private static function extractParameters(string $type, array $values): array
{
$types = self::$parameterTypes[$type] ??=
(static::PRAMETER_TYPE_HINTS[$type] ?? []) + array_reduce(
(new \ReflectionClass($type))->getConstructor()?->getParameters() ?? [],
static fn (array $types, \ReflectionParameter $refl): array => $types + [
$refl->getName() => $refl->getType() instanceof \ReflectionNamedType
&& !$refl->getType()->isBuiltin()
? $refl->getType()->getName()
: null,
],
[]
);
if (isset(self::$parameterTypes[$type])) {
$types = self::$parameterTypes[$type];
} else {
$types = static::PRAMETER_TYPE_HINTS[$type] ?? [];
$parameterRefls = (new \ReflectionClass($type))
->getConstructor()
?->getParameters() ?? [];
foreach ($parameterRefls as $refl) {
$paramName = $refl->getName();
if (\array_key_exists($paramName, $types)) {
continue;
}
$paramType = $refl->getType();
if ($paramType instanceof \ReflectionNamedType && !$paramType->isBuiltin()) {
$types[$paramName] = $paramType->getName();
} else {
$types[$paramName] = null;
}
}
self::$parameterTypes[$type] = $types;
}
$parameters = array_intersect_key($values, $types);
foreach ($parameters as $name => $parameter) {
$type = $types[$name];
if (null === $type || !\is_array($parameter)) {
continue;
}
$isArrayType = str_ends_with($type, '[]');
/**
* @var class-string
*/
$type = $isArrayType ? substr($type, 0, -2) : $type;
$shortName = (new \ReflectionClass($type))->getShortName();
if ($isArrayType) {
$parameters[$name] = [];
foreach ($parameter as $key => $values) {
$parameters[$name][$key] = Literal::new(
$shortName,
self::extractParameters($type, $values)
);
}
} else {
$parameters[$name] = Literal::new(
$shortName,
\ArrayObject::class === $type
? [$parameter]
: self::extractParameters($type, $parameter)
);
}
}
return $parameters;
}
/**
* Verifies that the operations' config is valid.
*
* @template T of array
*
* @param T $operations
*
* @return T
*/
private function validateClassOperations(array $operations): array
{
$resolver = new OptionsResolver();
$resolver->setDefaults(['item' => [], 'collection' => []]);
$resolver->setAllowedTypes('item', 'array');
$resolver->setAllowedTypes('collection', 'array');
/**
* @var T $operations
*/
$operations = $resolver->resolve($operations);
return $operations;
}
public function generatePropertyAttributes(Property $property, string $className): array
{
$arguments = [];
if ($property->rdfType()) {
if ($this->config['apiPlatformOldAttributes']) {
$arguments['iri'] = $property->rdfType();
} else {
$arguments['types'] = [$property->rdfType()];
}
}
return $property->isCustom ? [] : [new Attribute('ApiProperty', $arguments)];
}
public function generateUses(Class_ $class): array
{
if ($this->config['apiPlatformOldAttributes']) {
// @phpstan-ignore-next-line
return [new Use_(OldApiResource::class), new Use_(OldApiProperty::class)];
}
return [
new Use_(ApiResource::class),
new Use_(ApiProperty::class),
new Use_(Get::class),
new Use_(Put::class),
new Use_(Patch::class),
new Use_(Delete::class),
new Use_(GetCollection::class),
new Use_(Post::class),
];
}
}