-
Notifications
You must be signed in to change notification settings - Fork 611
/
Gql.php
648 lines (577 loc) · 21.4 KB
/
Gql.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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
<?php
/**
* @link https://craftcms.com/
* @copyright Copyright (c) Pixel & Tonic, Inc.
* @license https://craftcms.github.io/license/
*/
namespace craft\helpers;
use Craft;
use craft\base\ElementContainerFieldInterface;
use craft\base\ElementInterface;
use craft\errors\GqlException;
use craft\gql\base\Directive;
use craft\gql\ElementQueryConditionBuilder;
use craft\gql\GqlEntityRegistry;
use craft\models\EntryType;
use craft\models\GqlSchema;
use craft\models\Section;
use craft\models\Site;
use craft\services\Gql as GqlService;
use GraphQL\Language\AST\ListValueNode;
use GraphQL\Language\AST\VariableNode;
use GraphQL\Type\Definition\NonNull;
use GraphQL\Type\Definition\ResolveInfo;
use GraphQL\Type\Definition\Type;
use GraphQL\Type\Definition\UnionType;
/**
* Class Gql
*
* @author Pixel & Tonic, Inc. <support@pixelandtonic.com>
* @since 3.3.0
*/
class Gql
{
/**
* Returns whether the given component(s) are included in a schema’s scope.
*
* @param string|string[] $components The component(s) to check.
* @param GqlSchema|null $schema The GraphQL schema. If none is provided, the active schema will be used.
* @return bool
*/
public static function isSchemaAwareOf(array|string $components, ?GqlSchema $schema = null): bool
{
try {
$schema = self::_schema($schema);
} catch (GqlException) {
return false;
}
foreach ((array)$components as $component) {
$component = strtolower($component);
$found = false;
foreach ($schema->scope as $scopeComponent) {
if (str_starts_with(strtolower($scopeComponent), $component)) {
$found = true;
break;
}
}
if (!$found) {
return false;
}
}
return true;
}
/**
* Extracts all the allowed entities from a schema for the given action.
*
* @param string $action The action for which the entities should be extracted. Defaults to "read".
* @param GqlSchema|null $schema The GraphQL schema. If none is provided, the active schema will be used.
* @return array
*/
public static function extractAllowedEntitiesFromSchema(string $action = 'read', ?GqlSchema $schema = null): array
{
try {
$schema = self::_schema($schema);
} catch (GqlException) {
return [];
}
return $schema->getAllScopePairsForAction($action);
}
/**
* Returns whether the given component is included in a schema, for the given action.
*
* @param string $component The component to check.
* @param string $action The action. Defaults to "read".
* @param GqlSchema|null $schema The GraphQL schema. If none is provided, the active schema will be used.
* @return bool
* @throws GqlException
*/
public static function canSchema(string $component, string $action = 'read', ?GqlSchema $schema = null): bool
{
try {
$schema = self::_schema($schema);
} catch (GqlException) {
return false;
}
$search = strtolower("$component:$action");
foreach ($schema->scope as $scopeComponent) {
if (strtolower($scopeComponent) === $search) {
return true;
}
}
return false;
}
/**
* Return a list of all the actions the current schema is allowed for a given entity.
*
* @param string $entity
* @param GqlSchema|null $schema The GraphQL schema. If none is provided, the active schema will be used.
* @return array
*/
public static function extractEntityAllowedActions(string $entity, ?GqlSchema $schema = null): array
{
try {
$schema = self::_schema($schema);
} catch (GqlException) {
return [];
}
$actions = [];
$search = sprintf('%s:', strtolower($entity));
$searchLen = strlen($search);
foreach ($schema->scope as $scopeComponent) {
if (str_starts_with(strtolower($scopeComponent), $search)) {
$action = substr($scopeComponent, $searchLen);
$actions[$action] = true;
}
}
return array_keys($actions);
}
/**
* Return true if active schema can mutate tags.
*
* @param GqlSchema|null $schema The GraphQL schema. If none is provided, the active schema will be used.
* @return bool
* @since 3.5.0
*/
public static function canMutateTags(?GqlSchema $schema = null): bool
{
$allowedEntities = self::extractAllowedEntitiesFromSchema('edit', $schema);
return isset($allowedEntities['taggroups']);
}
/**
* Return true if active schema can mutate global sets.
*
* @param GqlSchema|null $schema The GraphQL schema. If none is provided, the active schema will be used.
* @return bool
* @since 3.5.0
*/
public static function canMutateGlobalSets(?GqlSchema $schema = null): bool
{
$allowedEntities = self::extractAllowedEntitiesFromSchema('edit', $schema);
return isset($allowedEntities['globalsets']);
}
/**
* Return true if active schema can mutate categories.
*
* @param GqlSchema|null $schema The GraphQL schema. If none is provided, the active schema will be used.
* @return bool
* @since 3.5.0
*/
public static function canMutateCategories(?GqlSchema $schema = null): bool
{
$allowedEntities = self::extractAllowedEntitiesFromSchema('edit', $schema);
return isset($allowedEntities['categorygroups']);
}
/**
* Return true if active schema can mutate assets.
*
* @param GqlSchema|null $schema The GraphQL schema. If none is provided, the active schema will be used.
* @return bool
* @since 3.5.0
*/
public static function canMutateAssets(?GqlSchema $schema = null): bool
{
$allowedEntities = self::extractAllowedEntitiesFromSchema('edit', $schema);
return isset($allowedEntities['volumes']);
}
/**
* Return true if active schema can query entries.
*
* @param GqlSchema|null $schema The GraphQL schema. If none is provided, the active schema will be used.
* @return bool
*/
public static function canQueryEntries(?GqlSchema $schema = null): bool
{
$allowedEntities = self::extractAllowedEntitiesFromSchema('read', $schema);
return isset($allowedEntities['sections']);
}
/**
* Return true if active schema can query assets.
*
* @param GqlSchema|null $schema The GraphQL schema. If none is provided, the active schema will be used.
* @return bool
*/
public static function canQueryAssets(?GqlSchema $schema = null): bool
{
$allowedEntities = self::extractAllowedEntitiesFromSchema('read', $schema);
return isset($allowedEntities['volumes']);
}
/**
* Return true if active schema can query categories.
*
* @param GqlSchema|null $schema The GraphQL schema. If none is provided, the active schema will be used.
* @return bool
*/
public static function canQueryCategories(?GqlSchema $schema = null): bool
{
$allowedEntities = self::extractAllowedEntitiesFromSchema('read', $schema);
return isset($allowedEntities['categorygroups']);
}
/**
* Return true if active schema can query tags.
*
* @param GqlSchema|null $schema The GraphQL schema. If none is provided, the active schema will be used.
* @return bool
*/
public static function canQueryTags(?GqlSchema $schema = null): bool
{
$allowedEntities = self::extractAllowedEntitiesFromSchema('read', $schema);
return isset($allowedEntities['taggroups']);
}
/**
* Return true if active schema can query global sets.
*
* @param GqlSchema|null $schema The GraphQL schema. If none is provided, the active schema will be used.
* @return bool
*/
public static function canQueryGlobalSets(?GqlSchema $schema = null): bool
{
$allowedEntities = self::extractAllowedEntitiesFromSchema('read', $schema);
return isset($allowedEntities['globalsets']);
}
/**
* Return true if active schema can query users.
*
* @param GqlSchema|null $schema The GraphQL schema. If none is provided, the active schema will be used.
* @return bool
*/
public static function canQueryUsers(?GqlSchema $schema = null): bool
{
$allowedEntities = self::extractAllowedEntitiesFromSchema('read', $schema);
return isset($allowedEntities['usergroups']);
}
/**
* Get (and create if needed) a union type by name, included types and a resolver function.
*
* @param string $typeName The union type name.
* @param array $includedTypes The type the union should include
* @param ?callable $resolveFunction The resolver function to use to resolve a specific type. If not provided,
* a default one will be used that is able to resolve Craft elements.
* @return mixed
*/
public static function getUnionType(string $typeName, array $includedTypes, ?callable $resolveFunction = null): mixed
{
$resolveFunction ??= fn(ElementInterface $value) => $value->getGqlTypeName();
return GqlEntityRegistry::getOrCreate($typeName, fn() => new UnionType([
'name' => $typeName,
'types' => $includedTypes,
'resolveType' => $resolveFunction,
]));
}
/**
* Wrap a GQL object type in a NonNull type.
*
* @param mixed $type
* @return mixed
*/
public static function wrapInNonNull(mixed $type): mixed
{
if ($type instanceof NonNull) {
return $type;
}
if (is_array($type)) {
$type['type'] = Type::nonNull($type['type']);
} else {
$type = Type::nonNull($type);
}
return $type;
}
/**
* Creates a temporary schema with full access to the GraphQL API.
*
* @return GqlSchema
* @since 3.4.0
*/
public static function createFullAccessSchema(): GqlSchema
{
$groups = Craft::$app->getGql()->getAllSchemaComponents();
$schema = new GqlSchema(['name' => 'Full Schema', 'uid' => '*']);
// Fetch all nested components
$traverser = function($group) use ($schema, &$traverser) {
foreach ($group as $component => $config) {
$schema->scope[] = $component;
if (isset($config['nested'])) {
$traverser($config['nested']);
}
}
};
foreach ($groups['queries'] as $group) {
$traverser($group);
}
foreach ($groups['mutations'] as $group) {
$traverser($group);
}
return $schema;
}
/**
* Apply directives (if any) to a resolved value according to source and resolve info.
*
* @param mixed $source
* @param ResolveInfo $resolveInfo
* @param mixed $value
* @return mixed
*/
public static function applyDirectives(mixed $source, ResolveInfo $resolveInfo, mixed $value): mixed
{
if (isset($resolveInfo->fieldNodes[0]->directives)) {
foreach ($resolveInfo->fieldNodes[0]->directives as $directive) {
/** @var Directive|false $directiveEntity */
$directiveEntity = GqlEntityRegistry::getEntity($directive->name->value);
// This can happen for built-in GraphQL directives in which case they will have been handled already, anyway
if (!$directiveEntity) {
continue;
}
$arguments = [];
if (isset($directive->arguments[0])) {
foreach ($directive->arguments as $argument) {
$arguments[$argument->name->value] = self::_convertArgumentValue($argument->value, $resolveInfo->variableValues);
}
}
$value = $directiveEntity::apply($source, $value, $arguments, $resolveInfo);
}
}
return $value;
}
/**
* Prepare arguments intended for asset transforms.
*
* @param array $arguments
* @return array|string
* @since 3.5.3
*/
public static function prepareTransformArguments(array $arguments): array|string
{
unset($arguments['immediately']);
if (!empty($arguments['handle'])) {
$transform = $arguments['handle'];
} elseif (!empty($arguments['transform'])) {
$transform = $arguments['transform'];
} else {
$transform = $arguments;
}
return $transform;
}
/**
* Return true if active schema can query for drafts.
*
* @param GqlSchema|null $schema The GraphQL schema. If none is provided, the active schema will be used.
* @return bool
* @since 3.6.8
*/
public static function canQueryDrafts(?GqlSchema $schema = null): bool
{
$allowedEntities = self::extractAllowedEntitiesFromSchema('read', $schema);
return isset($allowedEntities['elements']) && is_array($allowedEntities['elements']) && in_array('drafts', $allowedEntities['elements'], true);
}
/**
* Return true if active schema can query for revisions.
*
* @param GqlSchema|null $schema The GraphQL schema. If none is provided, the active schema will be used.
* @return bool
* @since 3.6.8
*/
public static function canQueryRevisions(?GqlSchema $schema = null): bool
{
$allowedEntities = self::extractAllowedEntitiesFromSchema('read', $schema);
return isset($allowedEntities['elements']) && is_array($allowedEntities['elements']) && in_array('revisions', $allowedEntities['elements'], true);
}
/**
* Return true if active schema can query for inactive elements.
*
* @param GqlSchema|null $schema The GraphQL schema. If none is provided, the active schema will be used.
* @return bool
* @since 3.6.8
*/
public static function canQueryInactiveElements(?GqlSchema $schema = null): bool
{
$allowedEntities = self::extractAllowedEntitiesFromSchema('read', $schema);
return isset($allowedEntities['elements']) && is_array($allowedEntities['elements']) && in_array('inactive', $allowedEntities['elements'], true);
}
/**
* Get a list of all allowed sites by Schema.
*
* @param GqlSchema|null $schema
* @return Site[]
* @since 4.0.0
*/
public static function getAllowedSites(?GqlSchema $schema = null): array
{
$allowedEntities = self::extractAllowedEntitiesFromSchema('read', $schema);
$allowedSiteUids = $allowedEntities['sites'] ?? [];
$sites = Craft::$app->getSites()->getAllSites(true);
return array_filter($sites, static function(Site $site) use ($allowedSiteUids) {
return in_array($site->uid, $allowedSiteUids, true);
});
}
/**
* @param mixed $value
* @param array $variableValues
* @return mixed
*/
private static function _convertArgumentValue(mixed $value, array $variableValues = []): mixed
{
if ($value instanceof VariableNode) {
return $variableValues[$value->name->value];
}
if ($value instanceof ListValueNode) {
return array_map(function($node) {
return self::_convertArgumentValue($node);
}, iterator_to_array($value->values));
}
return $value->value;
}
/**
* Looking at the resolve information and the source queried, return the field name or it's alias, if used.
*
* @param ResolveInfo $resolveInfo
* @param mixed $source
* @param array|null $context
* @return string
*/
public static function getFieldNameWithAlias(ResolveInfo $resolveInfo, mixed $source, ?array $context): string
{
$fieldName = is_array($resolveInfo->path) ? array_slice($resolveInfo->path, -1)[0] : $resolveInfo->fieldName;
$isAlias = $fieldName !== $resolveInfo->fieldName;
/** @var ElementQueryConditionBuilder|null $conditionBuilder */
$conditionBuilder = $context['conditionBuilder'] ?? null;
if ($isAlias) {
$cannotBeAliased = $conditionBuilder && !$conditionBuilder->canNodeBeAliased($fieldName);
$aliasNotEagerLoaded = !$source instanceof ElementInterface || $source->getEagerLoadedElements($fieldName) === null;
if ($cannotBeAliased || $aliasNotEagerLoaded) {
$fieldName = $resolveInfo->fieldName;
}
}
return $fieldName;
}
/**
* Shorthand for returning the complexity function for an eager-loaded field.
*
* @return callable
* @since 3.6.0
*/
public static function eagerLoadComplexity(): callable
{
return static function($childComplexity) {
return $childComplexity + GqlService::GRAPHQL_COMPLEXITY_EAGER_LOAD;
};
}
/**
* Shorthand for returning the complexity function for a field that will add a single query to execution.
*
* @return callable
* @since 3.6.0
*/
public static function singleQueryComplexity(): callable
{
return static function($childComplexity) {
return $childComplexity + GqlService::GRAPHQL_COMPLEXITY_QUERY;
};
}
/**
* Shorthand for returning the complexity function for a field that will add a single query to execution.
*
* @param int $baseComplexity The base complexity to use. Defaults to a single query.
* @return callable
* @since 3.6.7
*/
public static function relatedArgumentComplexity(int $baseComplexity = GqlService::GRAPHQL_COMPLEXITY_QUERY): callable
{
return static function($childComplexity, $args) use ($baseComplexity) {
$complexityScore = $childComplexity + $baseComplexity;
$relatedArguments = ['relatedToAssets', 'relatedToEntries', 'relatedToUsers', 'relatedToCategories', 'relatedToTags'];
foreach ($relatedArguments as $argumentName) {
if (!empty($args[$argumentName])) {
$complexityScore += GqlService::GRAPHQL_COMPLEXITY_QUERY * count((array)$args[$argumentName]);
}
}
if (!empty($args['relatedTo'])) {
$complexityScore += GqlService::GRAPHQL_COMPLEXITY_QUERY;
}
if (!empty($args['relatedToAll'])) {
$complexityScore += GqlService::GRAPHQL_COMPLEXITY_QUERY;
}
return $complexityScore;
};
}
/**
* Shorthand for returning the complexity function for a field that will generate a single query for every iteration.
*
* @return callable
* @since 3.6.0
*/
public static function nPlus1Complexity(): callable
{
return static function($childComplexity) {
return $childComplexity + GqlService::GRAPHQL_COMPLEXITY_NPLUS1;
};
}
/**
* Return all entry types a given (or loaded) schema contains.
*
* @return EntryType[]
*/
public static function getSchemaContainedEntryTypes(?GqlSchema $schema = null): array
{
$entryTypes = [];
foreach (static::getSchemaContainedSections($schema) as $section) {
foreach ($section->getEntryTypes() as $entryType) {
$entryTypes[$entryType->uid] = $entryType;
}
}
foreach (static::getSchemaContainedNestedEntryFields($schema) as $field) {
foreach ($field->getFieldLayoutProviders() as $provider) {
if ($provider instanceof EntryType) {
$entryTypes[$provider->uid] = $provider;
}
}
}
return array_values($entryTypes);
}
/**
* Returns all sections a given (or loaded) schema contains.
*
* @return Section[]
* @since 5.0.0
*/
public static function getSchemaContainedSections(?GqlSchema $schema = null): array
{
return array_filter(
Craft::$app->getEntries()->getAllSections(),
fn(Section $section) => static::isSchemaAwareOf("sections.$section->uid", $schema),
);
}
/**
* Returns all nested entry fields a given (or loaded) schema contains.
*
* @return ElementContainerFieldInterface[]
* @since 5.0.0
*/
public static function getSchemaContainedNestedEntryFields(?GqlSchema $schema = null): array
{
$fieldsService = Craft::$app->getFields();
/** @var ElementContainerFieldInterface[] $fields */
$fields = array_merge(...array_map(
fn(string $type) => $fieldsService->getFieldsByType($type),
$fieldsService->getNestedEntryFieldTypes()
));
return array_filter($fields, fn(ElementContainerFieldInterface $field) =>
static::isSchemaAwareOf("nestedentryfields.$field->uid", $schema));
}
/**
* @param GqlSchema|null $schema
* @return GqlSchema
* @throws GqlException
*/
private static function _schema(?GqlSchema $schema): GqlSchema
{
if ($schema !== null) {
return $schema;
}
try {
return Craft::$app->getGql()->getActiveSchema();
} catch (GqlException $e) {
Craft::warning("Could not get the active GraphQL schema: {$e->getMessage()}", __METHOD__);
Craft::$app->getErrorHandler()->logException($e);
throw $e;
}
}
}