forked from rebing/graphql-laravel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSelectFields.php
425 lines (370 loc) · 16.4 KB
/
SelectFields.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
413
414
415
416
417
418
419
420
421
422
423
424
425
<?php
declare(strict_types=1);
namespace Rebing\GraphQL\Support;
use Closure;
use Illuminate\Support\Arr;
use GraphQL\Language\AST\FieldNode;
use GraphQL\Error\InvariantViolation;
use GraphQL\Language\AST\ArgumentNode;
use GraphQL\Language\AST\VariableNode;
use GraphQL\Type\Definition\UnionType;
use GraphQL\Type\Definition\ResolveInfo;
use GraphQL\Type\Definition\WrappingType;
use GraphQL\Language\AST\SelectionSetNode;
use GraphQL\Language\AST\FragmentSpreadNode;
use GraphQL\Language\AST\InlineFragmentNode;
use GraphQL\Type\Definition\FieldDefinition;
use GraphQL\Language\AST\FragmentDefinitionNode;
use GraphQL\Type\Definition\Type as GraphqlType;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Database\Eloquent\Relations\MorphOne;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\MorphMany;
class SelectFields
{
/** @var array */
private static $args = [];
/** @var array */
private $select = [];
/** @var array */
private $relations = [];
/** @var array */
private static $privacyValidations = [];
/** @var ResolveInfo */
private $info;
const FOREIGN_KEY = 'foreignKey';
/**
* @param ResolveInfo $info
* @param GraphqlType $parentType
* @param array $args - arguments given with the query
*/
public function __construct(ResolveInfo $info, GraphqlType $parentType, array $args)
{
if ($parentType instanceof WrappingType) {
$parentType = $parentType->getWrappedType(true);
}
$this->info = $info;
self::$args = $args;
$fields = self::getSelectableFieldsAndRelations($this->getFieldSelection(5), $parentType);
$this->select = $fields[0];
$this->relations = $fields[1];
}
public function getFieldSelection($depth = 0)
{
$data = [];
if (! is_null($this->info->fieldNodes[0]->selectionSet)) {
/** @var FieldNode $fieldNode */
foreach ($this->info->fieldNodes as $fieldNode) {
if (! is_null($fieldNode->selectionSet)) {
$data = array_merge_recursive($data, $this->foldSelectionSet($fieldNode->selectionSet, $depth));
}
}
}
$fields['fields'] = $data;
$fields['args'] = self::$args;
return $fields;
}
private function foldSelectionSet(SelectionSetNode $selectionSet, $descend)
{
$fields = [];
foreach ($selectionSet->selections as $selectionNode) {
if ($selectionNode instanceof FieldNode) {
$fields[$selectionNode->name->value]['fields'] = $descend > 0 && ! empty($selectionNode->selectionSet)
? $this->foldSelectionSet($selectionNode->selectionSet, $descend - 1)
: true;
$fields[$selectionNode->name->value]['args'] = [];
foreach ($selectionNode->arguments as $argument) {
if ($argument->value instanceof VariableNode) {
$value = $this->info->variableValues[$argument->value->name->value] ?? null;
} else {
$value = $argument->value->value;
}
if ($argument instanceof ArgumentNode) {
$fields[$selectionNode->name->value]['args'][$argument->name->value] = $value;
}
}
} elseif ($selectionNode instanceof FragmentSpreadNode) {
$spreadName = $selectionNode->name->value;
if (isset($this->info->fragments[$spreadName])) {
/** @var FragmentDefinitionNode $fragment */
$fragment = $this->info->fragments[$spreadName];
$fields = array_merge_recursive($this->foldSelectionSet($fragment->selectionSet, $descend), $fields);
}
} elseif ($selectionNode instanceof InlineFragmentNode) {
$fields = array_merge_recursive($this->foldSelectionSet($selectionNode->selectionSet, $descend), $fields);
}
}
return $fields;
}
/**
* Retrieve the fields (top level) and relations that
* will be selected with the query.
*
* @param array $requestedFields
* @param GraphqlType $parentType
* @param Closure|null $customQuery
* @param bool $topLevel
* @return array|Closure - if first recursion, return an array,
* where the first key is 'select' array and second is 'with' array.
* On other recursions return a closure that will be used in with
*/
public static function getSelectableFieldsAndRelations(array $requestedFields, GraphqlType $parentType, ?Closure $customQuery = null, bool $topLevel = true)
{
$select = [];
$with = [];
if ($parentType instanceof WrappingType) {
$parentType = $parentType->getWrappedType(true);
}
$parentTable = self::getTableNameFromParentType($parentType);
$primaryKey = self::getPrimaryKeyFromParentType($parentType);
self::handleFields($requestedFields, $parentType, $select, $with);
// If a primary key is given, but not in the selects, add it
if (! is_null($primaryKey)) {
if (is_array($primaryKey)) {
foreach ($primaryKey as $key) {
$select[] = $parentTable ? ($parentTable.'.'.$key) : $key;
}
} else {
$primaryKey = $parentTable ? ($parentTable.'.'.$primaryKey) : $primaryKey;
if (! in_array($primaryKey, $select)) {
$select[] = $primaryKey;
}
}
}
if ($topLevel) {
return [$select, $with];
} else {
return function ($query) use ($with, $select, $customQuery, $requestedFields) {
if ($customQuery) {
$query = $customQuery($requestedFields['args'] ?? self::$args, $query);
}
$query->select($select);
$query->with($with);
};
}
}
/**
* Get the selects and withs from the given fields
* and recurse if necessary.
* @param array<string,mixed> $requestedFields
* @param GraphqlType $parentType
* @param array $select Passed by reference, adds further fields to select
* @param array $with Passed by reference, adds further relations
*/
protected static function handleFields(array $requestedFields, GraphqlType $parentType, array &$select, array &$with): void
{
$parentTable = self::isMongodbInstance($parentType) ? null : self::getTableNameFromParentType($parentType);
foreach ($requestedFields['fields'] as $key => $field) {
// Ignore __typename, as it's a special case
if ($key === '__typename') {
continue;
}
// Always select foreign key
if ($field === self::FOREIGN_KEY) {
self::addFieldToSelect($key, $select, $parentTable, false);
continue;
}
// If field doesn't exist on definition we don't select it
try {
if (method_exists($parentType, 'getField')) {
$fieldObject = $parentType->getField($key);
} else {
continue;
}
} catch (InvariantViolation $e) {
continue;
}
// First check if the field is even accessible
$canSelect = self::validateField($fieldObject);
if ($canSelect === true) {
// Add a query, if it exists
$customQuery = Arr::get($fieldObject->config, 'query');
// Check if the field is a relation that needs to be requested from the DB
$queryable = self::isQueryable($fieldObject->config);
// Pagination
if (is_a($parentType, config('graphql.pagination_type', PaginationType::class))) {
self::handleFields($field, $fieldObject->config['type']->getWrappedType(), $select, $with);
}
// With
elseif (is_array($field['fields']) && $queryable) {
if (isset($parentType->config['model'])) {
// Get the next parent type, so that 'with' queries could be made
// Both keys for the relation are required (e.g 'id' <-> 'user_id')
$relation = call_user_func([app($parentType->config['model']), $key]);
// Add the foreign key here, if it's a 'belongsTo'/'belongsToMany' relation
if (method_exists($relation, 'getForeignKey')) {
$foreignKey = $relation->getForeignKey();
} elseif (method_exists($relation, 'getQualifiedForeignPivotKeyName')) {
$foreignKey = $relation->getQualifiedForeignPivotKeyName();
} else {
$foreignKey = $relation->getQualifiedForeignKeyName();
}
$foreignKey = $parentTable ? ($parentTable.'.'.preg_replace('/^'.preg_quote($parentTable).'\./', '', $foreignKey)) : $foreignKey;
if (is_a($relation, MorphTo::class)) {
$foreignKeyType = $relation->getMorphType();
$foreignKeyType = $parentTable ? ($parentTable.'.'.$foreignKeyType) : $foreignKeyType;
if (! in_array($foreignKey, $select)) {
$select[] = $foreignKey;
}
if (! in_array($foreignKeyType, $select)) {
$select[] = $foreignKeyType;
}
} elseif (is_a($relation, BelongsTo::class)) {
if (! in_array($foreignKey, $select)) {
$select[] = $foreignKey;
}
}
// If 'HasMany', then add it in the 'with'
elseif ((is_a($relation, HasMany::class) || is_a($relation, MorphMany::class) || is_a($relation, HasOne::class) || is_a($relation, MorphOne::class))
&& ! array_key_exists($foreignKey, $field)) {
$segments = explode('.', $foreignKey);
$foreignKey = end($segments);
if (! array_key_exists($foreignKey, $field)) {
$field['fields'][$foreignKey] = self::FOREIGN_KEY;
}
}
// New parent type, which is the relation
$newParentType = $parentType->getField($key)->config['type'];
self::addAlwaysFields($fieldObject, $field, $parentTable, true);
$with[$key] = self::getSelectableFieldsAndRelations($field, $newParentType, $customQuery, false);
} else {
self::handleFields($field, $fieldObject->config['type'], $select, $with);
}
}
// Select
else {
$key = isset($fieldObject->config['alias'])
? $fieldObject->config['alias']
: $key;
self::addFieldToSelect($key, $select, $parentTable, false);
self::addAlwaysFields($fieldObject, $select, $parentTable);
}
}
// If privacy does not allow the field, return it as null
elseif ($canSelect === null) {
$fieldObject->resolveFn = function () {
};
}
// If allowed field, but not selectable
elseif ($canSelect === false) {
self::addAlwaysFields($fieldObject, $select, $parentTable);
}
}
// If parent type is an union we select all fields
// because we don't know which other fields are required
if (is_a($parentType, UnionType::class)) {
$select = ['*'];
}
}
/**
* Check the privacy status, if it's given.
*
* @param FieldDefinition $fieldObject
* @return bool|null - true, if selectable; false, if not selectable, but allowed;
* null, if not allowed
*/
protected static function validateField(FieldDefinition $fieldObject): ?bool
{
$selectable = true;
// If not a selectable field
if (isset($fieldObject->config['selectable']) && $fieldObject->config['selectable'] === false) {
$selectable = false;
}
if (isset($fieldObject->config['privacy'])) {
$privacyClass = $fieldObject->config['privacy'];
// If privacy given as a closure
if (is_callable($privacyClass) && call_user_func($privacyClass, self::$args) === false) {
$selectable = null;
}
// If Privacy class given
elseif (is_string($privacyClass)) {
if (Arr::has(self::$privacyValidations, $privacyClass)) {
$validated = self::$privacyValidations[$privacyClass];
} else {
$validated = call_user_func([app($privacyClass), 'fire'], self::$args);
self::$privacyValidations[$privacyClass] = $validated;
}
if (! $validated) {
$selectable = null;
}
}
}
return $selectable;
}
/**
* Determines whether the fieldObject is queryable.
*
* @param array $fieldObject
*
* @return bool
*/
private static function isQueryable(array $fieldObject): bool
{
return Arr::get($fieldObject, 'is_relation', true) === true;
}
/**
* Add selects that are given by the 'always' attribute.
*
* @param FieldDefinition $fieldObject
* @param array $select Passed by reference, adds further fields to select
* @param string|null $parentTable
* @param bool $forRelation
*/
protected static function addAlwaysFields(FieldDefinition $fieldObject, array &$select, ?string $parentTable, bool $forRelation = false): void
{
if (isset($fieldObject->config['always'])) {
$always = $fieldObject->config['always'];
if (is_string($always)) {
$always = explode(',', $always);
}
// Get as 'field' => true
foreach ($always as $field) {
self::addFieldToSelect($field, $select, $parentTable, $forRelation);
}
}
}
/**
* @param string $field
* @param array $select Passed by reference, adds further fields to select
* @param string|null $parentTable
* @param bool $forRelation
*/
protected static function addFieldToSelect(string $field, array &$select, ?string $parentTable, bool $forRelation): void
{
if ($forRelation && ! array_key_exists($field, $select)) {
$select[$field] = true;
} elseif (! $forRelation && ! in_array($field, $select)) {
$field = $parentTable ? ($parentTable.'.'.$field) : $field;
if (! in_array($field, $select)) {
$select[] = $field;
}
}
}
private static function getPrimaryKeyFromParentType(GraphqlType $parentType): ?string
{
return isset($parentType->config['model']) ? app($parentType->config['model'])->getKeyName() : null;
}
private static function getTableNameFromParentType(GraphqlType $parentType): ?string
{
return isset($parentType->config['model']) ? app($parentType->config['model'])->getTable() : null;
}
private static function isMongodbInstance(GraphqlType $parentType): bool
{
$mongoType = 'Jenssegers\Mongodb\Eloquent\Model';
return isset($parentType->config['model']) ? app($parentType->config['model']) instanceof $mongoType : false;
}
public function getSelect(): array
{
return $this->select;
}
public function getRelations(): array
{
return $this->relations;
}
public function getResolveInfo(): ResolveInfo
{
return $this->info;
}
}