/
QueryHandler.php
412 lines (366 loc) · 12.3 KB
/
QueryHandler.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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
<?php
namespace SilverStripe\GraphQL\QueryHandler;
use GraphQL\Error\Error;
use GraphQL\Error\SyntaxError;
use GraphQL\Error\UserError;
use GraphQL\Executor\ExecutionResult;
use GraphQL\GraphQL;
use GraphQL\Language\AST\DocumentNode;
use GraphQL\Language\AST\NodeKind;
use GraphQL\Language\Lexer;
use GraphQL\Language\Parser;
use GraphQL\Language\Source;
use GraphQL\Language\SourceLocation;
use GraphQL\Language\Token;
use GraphQL\Type\Schema as GraphQLSchema;
use GraphQL\Validator\DocumentValidator;
use GraphQL\Validator\Rules\QueryComplexity;
use GraphQL\Validator\Rules\QueryDepth;
use SilverStripe\Control\Director;
use SilverStripe\Core\Config\Configurable;
use SilverStripe\Core\Extensible;
use SilverStripe\Core\Injector\Injectable;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\GraphQL\Middleware\QueryMiddleware;
use SilverStripe\GraphQL\Permission\MemberAware;
use SilverStripe\GraphQL\PersistedQuery\PersistedQueryMappingProvider;
use SilverStripe\GraphQL\PersistedQuery\PersistedQueryProvider;
use SilverStripe\GraphQL\Schema\Interfaces\ContextProvider;
use SilverStripe\GraphQL\Schema\Schema;
use SilverStripe\GraphQL\Schema\SchemaConfig;
use SilverStripe\ORM\ValidationException;
/**
* This class is responsible for taking query information from a controller,
* processing it through middlewares, extracting the results from the GraphQL schema,
* and formatting it into a suitable JSON response.
*/
class QueryHandler implements
QueryHandlerInterface,
PersistedQueryProvider
{
use Extensible;
use Injectable;
use Configurable;
use MemberAware;
/**
* @var ContextProvider[]
*/
private array $contextProviders = [];
private array $errorFormatter = [self::class, 'formatError'];
/**
* @config
* @var callable|null
*/
private $errorHandler = null;
/**
* @var QueryMiddleware[]
*/
private array $middlewares = [];
/**
* QueryHandler constructor.
* @param ContextProvider[] $contextProviders
*/
public function __construct(array $contextProviders = [])
{
foreach ($contextProviders as $contextProvider) {
$this->addContextProvider($contextProvider);
}
}
/**
* @param GraphQLSchema $schema
* @param string|DocumentNode $query
* @param array|null $vars
* @return array
*/
public function query(GraphQLSchema $schema, $query, ?array $vars = []): array
{
$executionResult = $this->queryAndReturnResult($schema, $query, $vars);
// Already in array form
if (is_array($executionResult)) {
return $executionResult;
}
return $this->serialiseResult($executionResult);
}
/**
* @param GraphQLSchema $schema
* @param string|DocumentNode $query
* @param array|null $vars
* @return array|ExecutionResult
*/
public function queryAndReturnResult(GraphQLSchema $schema, $query, ?array $vars = [])
{
if ($this->errorHandler) {
set_error_handler($this->errorHandler);
}
$context = $this->getContext();
$last = function ($schema, $query, $context, $vars) {
if (is_string($query)) {
$this->validateQueryBeforeParsing($query, $context);
}
$validationRules = DocumentValidator::allRules();
if (isset($context[SchemaConfigProvider::KEY])) {
/** @var SchemaConfig $config */
$config = $context[SchemaConfigProvider::KEY];
$maxDepth = $config->get('max_query_depth');
$maxComplexity = $config->get('max_query_complexity');
if ($maxDepth) {
$validationRules[QueryDepth::class] = new QueryDepth($maxDepth);
}
if ($maxComplexity) {
$validationRules[QueryComplexity::class] = new QueryComplexity($maxComplexity);
}
}
return GraphQL::executeQuery($schema, $query, null, $context, $vars, null, null, $validationRules);
};
return $this->callMiddleware($schema, $query, $context, $vars ?? [], $last);
}
/**
* Validate a query before parsing it in case there are issues we can catch early.
*/
public function validateQueryBeforeParsing(string $query, array $context): void
{
if (!isset($context[SchemaConfigProvider::KEY])) {
return;
}
/** @var SchemaConfig $config */
$config = $context[SchemaConfigProvider::KEY];
$maxNodes = $config->get('max_query_nodes');
if (!$maxNodes) {
return;
}
$lexer = new Lexer(new Source($query));
$numNodes = 0;
// Check how many nodes there are in this query
do {
$next = $lexer->advance();
if ($next->kind === Token::NAME) {
$numNodes++;
}
} while ($next->kind !== Token::EOF && $numNodes <= $maxNodes);
// Throw a UserError if there are too many nodes
if ($numNodes > $maxNodes) {
throw new UserError("GraphQL query body must not be longer than $maxNodes nodes.");
}
}
/**
* get query from persisted id, return null if not found
*
* @param string $id
* @return string|null
*/
public function getQueryFromPersistedID(string $id): ?string
{
$provider = Injector::inst()->get(PersistedQueryMappingProvider::class);
return $provider->getByID($id);
}
/**
* Get global context to pass to $context for all queries
*
* @return array
*/
public function getContext(): array
{
$context = [];
foreach ($this->contextProviders as $provider) {
$context = array_merge($context, $provider->provideContext());
}
return $context;
}
/**
* @param ContextProvider $provider
* @return $this
*/
public function addContextProvider(ContextProvider $provider): QueryHandlerInterface
{
$this->contextProviders[] = $provider;
return $this;
}
/**
* Serialise a Graphql result object for output
*
* @param ExecutionResult $executionResult
* @return array
*/
public function serialiseResult(ExecutionResult $executionResult): array
{
// Format object
if (!empty($executionResult->errors)) {
return [
'data' => $executionResult->data,
'errors' => array_map($this->errorFormatter, $executionResult->errors ?? []),
];
} else {
return [
'data' => $executionResult->data,
];
}
}
/**
* @param callable $errorFormatter
* @return QueryHandler
*/
public function setErrorFormatter(callable $errorFormatter): self
{
$this->errorFormatter = $errorFormatter;
return $this;
}
/**
* @param callable $errorHandler
* @return QueryHandler
*/
public function setErrorHandler(callable $errorHandler): self
{
$this->errorHandler = $errorHandler;
return $this;
}
/**
* @return QueryMiddleware[]
*/
public function getMiddlewares(): array
{
return $this->middlewares;
}
/**
* @param QueryMiddleware[] $middlewares
* @return $this
*/
public function setMiddlewares(array $middlewares): self
{
foreach ($middlewares as $middleware) {
if ($middleware instanceof QueryMiddleware) {
$this->addMiddleware($middleware);
}
}
return $this;
}
/**
* @param QueryMiddleware $middleware
* @return $this
*/
public function addMiddleware(QueryMiddleware $middleware): self
{
$this->middlewares[] = $middleware;
return $this;
}
/**
* Call middleware to evaluate a graphql query
*
* @param GraphQLSchema $schema
* @param string $query Query to invoke
* @param array $context
* @param array $params Variables passed to this query
* @param callable $last The callback to call after all middlewares
* @return ExecutionResult|array
*/
protected function callMiddleware(GraphQLSchema $schema, string $query, array $context, array $params, callable $last)
{
// Reverse middlewares
$next = $last;
// Filter out any middlewares that are set to `false`, e.g. via config
$middlewares = array_reverse(array_filter($this->getMiddlewares() ?? []));
foreach ($middlewares as $middleware) {
$next = function ($schema, $query, $context, $params) use ($middleware, $next) {
return $middleware->process($schema, $query, $context, $params, $next);
};
}
$result = $next($schema, $query, $context, $params);
return $result;
}
/**
* More verbose error display defaults.
*
* @param Error $exception
* @return array
*/
public static function formatError(Error $exception): array
{
$current = $exception;
$relevant = $exception->getPrevious() ?: $current;
$error = [
'message' => $relevant->getMessage(),
];
if (Director::isDev()) {
$error['code'] = $relevant->getCode();
$error['file'] = $relevant->getFile();
$error['line'] = $relevant->getLine();
$error['trace'] = json_encode($relevant->getTrace(), JSON_PRETTY_PRINT);
}
$locations = $current->getLocations();
if (!empty($locations)) {
$error['locations'] = array_map(function (SourceLocation $loc) {
return $loc->toArray();
}, $locations ?? []);
}
if ($relevant instanceof ValidationException) {
$error['validation'] = $relevant->getResult()->getMessages();
}
return $error;
}
/**
* @param string $query
* @return bool
* @throws SyntaxError
*/
public static function isMutation(string $query): bool
{
// Simple string matching as a first check to prevent unnecessary static analysis
if (stristr($query ?? '', 'mutation') === false) {
return false;
}
// If "mutation" is the first expression in the query, then it's a mutation.
if (preg_match('/^\s*' . preg_quote('mutation', '/') . '/', $query ?? '')) {
return true;
}
// Otherwise, bring in the big guns.
$document = Parser::parse(new Source($query));
$defs = $document->definitions;
foreach ($defs as $statement) {
$options = [
NodeKind::OPERATION_DEFINITION,
NodeKind::OPERATION_TYPE_DEFINITION
];
if (!in_array($statement->kind, $options ?? [], true)) {
continue;
}
if ($statement->operation === 'mutation') {
return true;
}
}
return false;
}
/**
* @param DocumentNode $document
* @param bool $preferStatementName If true, use query <MyQueryName(Vars..)>. If false, use the actual field name.
* @return string
*/
public static function getOperationName(DocumentNode $document, bool $preferStatementName = true): string
{
$defs = $document->definitions;
foreach ($defs as $statement) {
$options = [
NodeKind::OPERATION_DEFINITION,
NodeKind::OPERATION_TYPE_DEFINITION
];
if (!in_array($statement->kind, $options ?? [], true)) {
continue;
}
if (in_array($statement->operation, ['query', 'mutation'])) {
// If the operation was given a name, use that
$name = $statement->name;
if ($name && $name->value && $preferStatementName) {
return $name->value;
}
$selectionSet = $statement->selectionSet;
if ($selectionSet) {
$selections = $selectionSet->selections;
if (!empty($selections)) {
$firstField = $selections[0];
return $firstField->name->value;
}
}
return $statement->operation;
}
}
return 'graphql';
}
}