-
-
Notifications
You must be signed in to change notification settings - Fork 266
/
Copy pathField.php
353 lines (285 loc) · 9.95 KB
/
Field.php
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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
<?php
declare(strict_types = 1);
namespace Rebing\GraphQL\Support;
use Closure;
use GraphQL\Type\Definition\ResolveInfo;
use GraphQL\Type\Definition\Type as GraphQLType;
use Illuminate\Contracts\Validation\Validator as ValidatorContract;
use Illuminate\Pipeline\Pipeline;
use Illuminate\Support\Facades\Validator;
use InvalidArgumentException;
use Rebing\GraphQL\Error\AuthorizationError;
use Rebing\GraphQL\Error\ValidationError;
use Rebing\GraphQL\Support\AliasArguments\AliasArguments;
use Rebing\GraphQL\Support\Facades\GraphQL;
use ReflectionMethod;
/**
* @property string $name
*/
abstract class Field
{
/** @var array<string,mixed> */
protected $attributes = [];
/** @var list<class-string> */
protected $middleware = [];
/**
* Override this in your queries or mutations
* to provide custom authorization.
*
* @param mixed $root
* @param mixed $ctx
*/
public function authorize($root, array $args, $ctx, ?ResolveInfo $resolveInfo = null, ?Closure $getSelectFields = null): bool
{
return true;
}
public function attributes(): array
{
return [];
}
abstract public function type(): GraphQLType;
/**
* @return array<string,array<string,mixed>>
*/
public function args(): array
{
return [];
}
/**
* Define custom Laravel Validator messages as per Laravel 'custom error messages'.
*
* @param array $args submitted arguments
*/
public function validationErrorMessages(array $args = []): array
{
return [];
}
/**
* Define custom Laravel Validator attributes as per Laravel 'custom attributes'.
*
* @param array<string,mixed> $args submitted arguments
* @return array<string,string>
*/
public function validationAttributes(array $args = []): array
{
return [];
}
/**
* @param array<string,mixed> $args
* @return array<string,mixed>
*/
protected function rules(array $args = []): array
{
return [];
}
/**
* @param array<string,mixed> $arguments
* @return array<string,mixed>
*/
public function getRules(array $arguments = []): array
{
$rules = $this->rules($arguments);
$argsRules = (new Rules($this->args(), $arguments))->get();
return array_merge($argsRules, $rules);
}
/**
* @param array<string,mixed> $arguments
* @param array<string,mixed> $rules
*/
protected function validateArguments(array $arguments, array $rules): void
{
$validator = $this->getValidator($arguments, $rules);
if ($validator->fails()) {
throw new ValidationError('validation', $validator);
}
}
/**
* @param array<string,mixed> $fieldsAndArgumentsSelection
*/
public function validateFieldArguments(array $fieldsAndArgumentsSelection): void
{
$argsRules = (new RulesInFields($this->type(), $fieldsAndArgumentsSelection))->get();
if (!$argsRules) {
return;
}
$validator = $this->getValidator($fieldsAndArgumentsSelection, $argsRules);
if ($validator->fails()) {
throw new ValidationError('validation', $validator);
}
}
public function getValidator(array $args, array $rules): ValidatorContract
{
// allow our error messages to be customised
$messages = $this->validationErrorMessages($args);
// allow our attributes to be customized
$attributes = $this->validationAttributes($args);
return Validator::make($args, $rules, $messages, $attributes);
}
/**
* @return list<class-string>
*/
protected function getMiddleware(): array
{
return $this->middleware;
}
/**
* @return list<class-string|object>
* @phpstan-param list<string> $middleware
*/
protected function appendGlobalMiddlewares(array $middleware): array
{
return array_merge($middleware, GraphQL::getGlobalResolverMiddlewares());
}
protected function getResolver(): ?Closure
{
$resolver = $this->originalResolver();
if (!$resolver) {
return null;
}
return function ($root, ...$arguments) use ($resolver) {
$middleware = $this->appendGlobalMiddlewares($this->getMiddleware());
return app()->make(Pipeline::class)
->send(array_merge([$this], $arguments))
->through($middleware)
->via('resolve')
->then(function ($arguments) use ($middleware, $resolver, $root) {
$result = $resolver($root, ...\array_slice($arguments, 1));
foreach ($middleware as $name) {
/** @var Middleware $instance */
$instance = \is_object($name) ? $name : app()->make($name);
if (method_exists($instance, 'terminate')) {
app()->terminating(function () use ($arguments, $instance, $result): void {
$instance->terminate($this, ...\array_slice($arguments, 1), ...[$result]);
});
}
}
return $result;
});
};
}
protected function originalResolver(): ?Closure
{
if (!method_exists($this, 'resolve')) {
return null;
}
$resolver = [$this, 'resolve'];
$authorize = [$this, 'authorize'];
return function () use ($resolver, $authorize) {
// 0 - the "root" object; `null` for queries, otherwise the parent of a type
// 1 - the provided `args` of the query or type (if applicable), empty array otherwise
// 2 - the `$contextValue` (usually set via a GraphQL execution middleware, e.g. `AddAuthUserContextValueMiddleware`)
// 3 - \GraphQL\Type\Definition\ResolveInfo as provided by the underlying GraphQL PHP library
// 4 (!) - added by this library, encapsulates creating a `SelectFields` instance
$arguments = \func_get_args();
// Validate mutation arguments
$args = $arguments[1];
$rules = $this->getRules($args);
if ($rules) {
$this->validateArguments($args, $rules);
}
$fieldsAndArguments = $arguments[3]->lookAhead()->queryPlan();
// Validate arguments in fields
$this->validateFieldArguments($fieldsAndArguments);
$arguments[1] = $this->getArgs($arguments);
// Authorize
if (true != \call_user_func_array($authorize, $arguments)) {
throw new AuthorizationError($this->getAuthorizationMessage());
}
$method = new ReflectionMethod($this, 'resolve');
$additionalParams = \array_slice($method->getParameters(), 3);
$additionalArguments = array_map(function ($param) use ($arguments, $fieldsAndArguments) {
$paramType = $param->getType();
if ($paramType->isBuiltin()) {
throw new InvalidArgumentException("'$param->name' could not be injected");
}
$className = $paramType->getName();
if (Closure::class === $className) {
return function () use ($arguments, $fieldsAndArguments) {
return $this->instanciateSelectFields($arguments, $fieldsAndArguments);
};
}
if ($this->selectFieldClass() === $className) {
return $this->instanciateSelectFields($arguments, $fieldsAndArguments);
}
if (ResolveInfo::class === $className) {
return $arguments[3];
}
return app()->make($className);
}, $additionalParams);
return \call_user_func_array($resolver, array_merge(
[$arguments[0], $arguments[1], $arguments[2]],
$additionalArguments
));
};
}
/**
* @param array<int,mixed> $arguments
* @param array<string,mixed> $fieldsAndArguments
*/
protected function instanciateSelectFields(array $arguments, array $fieldsAndArguments): SelectFields
{
$ctx = $arguments[2] ?? null;
$selectFieldsClass = $this->selectFieldClass();
return new $selectFieldsClass($this->type(), $arguments[1], $ctx, $fieldsAndArguments);
}
/**
* @return class-string<SelectFields>
*/
protected function selectFieldClass(): string
{
return SelectFields::class;
}
protected function aliasArgs(array $arguments): array
{
return (new AliasArguments($this->args(), $arguments[1]))->get();
}
protected function getArgs(array $arguments): array
{
return $this->aliasArgs($arguments);
}
/**
* Get the attributes from the container.
*/
public function getAttributes(): array
{
$attributes = $this->attributes();
$attributes = array_merge(
$this->attributes,
['args' => $this->args()],
$attributes
);
$attributes['type'] = $this->type();
$resolver = $this->getResolver();
if (isset($resolver)) {
$attributes['resolve'] = $resolver;
}
return $attributes;
}
public function getAuthorizationMessage(): string
{
return 'Unauthorized';
}
/**
* @return array<string,mixed>
*/
public function toArray(): array
{
return $this->getAttributes();
}
/**
* Dynamically retrieve the value of an attribute.
*
* @param string $key
*
* @return mixed
*/
public function __get($key)
{
$attributes = $this->getAttributes();
return $attributes[$key] ?? null;
}
public function __set(string $key, $value): void
{
$this->attributes[$key] = $value;
}
}