-
-
Notifications
You must be signed in to change notification settings - Fork 970
Expand file tree
/
Copy pathOperationDefaultsTrait.php
More file actions
245 lines (199 loc) · 9.06 KB
/
Copy pathOperationDefaultsTrait.php
File metadata and controls
245 lines (199 loc) · 9.06 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
<?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\Metadata\Resource\Factory;
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\CollectionOperationInterface;
use ApiPlatform\Metadata\Delete;
use ApiPlatform\Metadata\Exception\RuntimeException;
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\GetCollection;
use ApiPlatform\Metadata\GraphQl\DeleteMutation;
use ApiPlatform\Metadata\GraphQl\Mutation;
use ApiPlatform\Metadata\GraphQl\Operation as GraphQlOperation;
use ApiPlatform\Metadata\GraphQl\Query;
use ApiPlatform\Metadata\GraphQl\QueryCollection;
use ApiPlatform\Metadata\GraphQl\Subscription;
use ApiPlatform\Metadata\HttpOperation;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\Metadata\Operations;
use ApiPlatform\Metadata\Patch;
use ApiPlatform\Metadata\Post;
use ApiPlatform\Metadata\Util\CamelCaseToSnakeCaseNameConverter;
use ApiPlatform\State\ApiResource\Error;
use ApiPlatform\State\CreateProvider;
use ApiPlatform\Validator\Exception\ValidationException;
use Psr\Log\LoggerInterface;
/**
* @internal since api-platform 4.2
*/
trait OperationDefaultsTrait
{
private CamelCaseToSnakeCaseNameConverter $camelCaseToSnakeCaseNameConverter;
private array $defaults = [];
private LoggerInterface $logger;
private function addGlobalDefaults(ApiResource|Operation $operation): ApiResource|Operation
{
// Do not add global defaults for internal resources:
if (\in_array($operation->getClass(), [Error::class, ValidationException::class], true)) {
return $operation;
}
$extraProperties = $this->defaults['extra_properties'] ?? [];
foreach ($this->defaults as $key => $value) {
if ('operations' === $key) {
continue;
}
$upperKey = ucfirst($this->camelCaseToSnakeCaseNameConverter->denormalize($key));
$getter = 'get'.$upperKey;
if (!method_exists($operation, $getter)) {
if (!isset($extraProperties[$key])) {
$extraProperties[$key] = $value;
}
continue;
}
$currentValue = $operation->{$getter}();
if (\is_array($currentValue) && $currentValue) {
if (\is_string($value)) {
$value = [$value];
}
$operation = $operation->{'with'.$upperKey}(array_merge($value, $currentValue));
}
if (null !== $currentValue || null === $value) {
continue;
}
$operation = $operation->{'with'.$upperKey}($value);
}
return $operation->withExtraProperties(array_merge($extraProperties, $operation->getExtraProperties()));
}
private function getResourceWithDefaults(string $resourceClass, string $shortName, ApiResource $resource): ApiResource
{
$resource = $resource
->withShortName($resource->getShortName() ?? $shortName)
->withClass($resource->getClass() ?? $resourceClass);
return $this->addGlobalDefaults($resource);
}
/**
* @return Operations<HttpOperation>|array<int,HttpOperation>
*/
private function getDefaultHttpOperations(ApiResource $resource): iterable
{
if (enum_exists($resource->getClass())) {
return new Operations([new GetCollection(paginationEnabled: false), new Get()]);
}
if (($defaultOperations = $this->defaults['operations'] ?? null) && null === $resource->getOperations()) {
$operations = [];
foreach ($defaultOperations as $defaultOperation) {
$operation = new $defaultOperation();
if ($operation instanceof Post && $resource->getUriTemplate() && !$resource->getProvider()) {
$operation = $operation->withProvider(CreateProvider::class);
}
$operations[] = $operation;
}
return new Operations($operations);
}
$post = new Post();
if ($resource->getUriTemplate() && !$resource->getProvider()) {
$post = $post->withProvider(CreateProvider::class);
}
return [new Get(), new GetCollection(), $post, new Patch(), new Delete()];
}
private function addDefaultGraphQlOperations(ApiResource $resource): ApiResource
{
$operations = enum_exists($resource->getClass()) ? [new Query(), new QueryCollection(paginationEnabled: false)] : [new Query(), new QueryCollection(), (new Mutation())->withName('update'), (new DeleteMutation())->withName('delete'), (new Mutation())->withName('create')];
$graphQlOperations = [];
foreach ($operations as $operation) {
[$key, $operation] = $this->getOperationWithDefaults($resource, $operation);
$graphQlOperations[$key] = $operation;
}
if ($resource->getMercure()) {
[$key, $operation] = $this->getOperationWithDefaults($resource, (new Subscription())->withDescription("Subscribes to the update event of a {$operation->getShortName()}."));
$graphQlOperations[$key] = $operation;
}
return $resource->withGraphQlOperations($graphQlOperations);
}
/**
* Adds nested query operations if there are no existing query ones on the resource.
* They are needed when the resource is queried inside a root query, using a relation.
* Since the nested argument is used, root queries will not be generated for these operations.
*/
private function completeGraphQlOperations(ApiResource $resource): ApiResource
{
$graphQlOperations = $resource->getGraphQlOperations();
$hasQueryOperation = false;
$hasQueryCollectionOperation = false;
foreach ($graphQlOperations as $operation) {
if ($operation instanceof Query && !$operation instanceof QueryCollection) {
$hasQueryOperation = true;
}
if ($operation instanceof QueryCollection) {
$hasQueryCollectionOperation = true;
}
}
if (!$hasQueryOperation) {
$queryOperation = (new Query())->withNested(true);
$graphQlOperations[$queryOperation->getName()] = $queryOperation;
}
if (!$hasQueryCollectionOperation) {
$queryCollectionOperation = (new QueryCollection())->withNested(true);
$graphQlOperations[$queryCollectionOperation->getName()] = $queryCollectionOperation;
}
return $resource->withGraphQlOperations($graphQlOperations);
}
/**
* @param list<string> $ignoredOptions
*
* @return array<int,mixed>
*/
private function getOperationWithDefaults(ApiResource $resource, Operation $operation, bool $generated = false, array $ignoredOptions = []): array
{
$operation = $operation->cascadeFromResource($resource, $ignoredOptions)->withExtraProperties(array_merge(
$resource->getExtraProperties(),
$operation->getExtraProperties(),
$generated ? ['generated_operation' => true] : []
));
// Add global defaults attributes to the operation
$operation = $this->addGlobalDefaults($operation);
if ($operation instanceof GraphQlOperation) {
if (!$operation->getName()) {
throw new RuntimeException('No GraphQL operation name.');
}
if ($operation instanceof Mutation && null === $operation->getDescription()) {
$operation = $operation->withDescription(ucfirst("{$operation->getName()}s a {$resource->getShortName()}."));
}
return [$operation->getName(), $operation];
}
if (!$operation instanceof HttpOperation) {
throw new RuntimeException(\sprintf('Operation should be an instance of "%s"', HttpOperation::class));
}
if (!$operation->getName() && $operation->getRouteName()) {
/** @var HttpOperation $operation */
$operation = $operation->withName($operation->getRouteName());
}
$operationName = $operation->getName() ?? $this->getDefaultOperationName($operation, $resource->getClass());
return [
$operationName,
$operation,
];
}
private function getDefaultShortname(string $resourceClass): string
{
return (false !== $pos = strrpos($resourceClass, '\\')) ? substr($resourceClass, $pos + 1) : $resourceClass;
}
private function getDefaultOperationName(HttpOperation $operation, string $resourceClass): string
{
$path = ($operation->getRoutePrefix() ?? '').($operation->getUriTemplate() ?? '');
return \sprintf(
'_api_%s_%s%s',
$path ?: ($operation->getShortName() ?? $this->getDefaultShortname($resourceClass)),
strtolower($operation->getMethod()),
$operation instanceof CollectionOperationInterface ? '_collection' : ''
);
}
}