-
Notifications
You must be signed in to change notification settings - Fork 638
/
Copy pathGql.php
1925 lines (1694 loc) · 60.8 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
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* @link https://craftcms.com/
* @copyright Copyright (c) Pixel & Tonic, Inc.
* @license https://craftcms.github.io/license/
*/
namespace craft\services;
use Craft;
use craft\base\ElementContainerFieldInterface;
use craft\base\ElementInterface as BaseElementInterface;
use craft\base\FieldInterface;
use craft\base\GqlInlineFragmentFieldInterface;
use craft\behaviors\FieldLayoutBehavior;
use craft\db\Query as DbQuery;
use craft\db\Table;
use craft\enums\CmsEdition;
use craft\errors\GqlException;
use craft\events\ConfigEvent;
use craft\events\DefineGqlValidationRulesEvent;
use craft\events\ExecuteGqlQueryEvent;
use craft\events\RegisterGqlDirectivesEvent;
use craft\events\RegisterGqlMutationsEvent;
use craft\events\RegisterGqlQueriesEvent;
use craft\events\RegisterGqlSchemaComponentsEvent;
use craft\events\RegisterGqlTypesEvent;
use craft\gql\ArgumentManager;
use craft\gql\base\Directive;
use craft\gql\base\GeneratorInterface;
use craft\gql\base\SingularTypeInterface;
use craft\gql\directives\FormatDateTime;
use craft\gql\directives\Markdown;
use craft\gql\directives\Money;
use craft\gql\directives\ParseRefs;
use craft\gql\directives\StripTags;
use craft\gql\directives\Transform;
use craft\gql\directives\Trim;
use craft\gql\ElementQueryConditionBuilder;
use craft\gql\GqlEntityRegistry;
use craft\gql\interfaces\Element as ElementInterface;
use craft\gql\interfaces\elements\Address as AddressInterface;
use craft\gql\interfaces\elements\Asset as AssetInterface;
use craft\gql\interfaces\elements\Category as CategoryInterface;
use craft\gql\interfaces\elements\Entry as EntryInterface;
use craft\gql\interfaces\elements\GlobalSet as GlobalSetInterface;
use craft\gql\interfaces\elements\Tag as TagInterface;
use craft\gql\interfaces\elements\User as UserInterface;
use craft\gql\mutations\Asset as AssetMutation;
use craft\gql\mutations\Category as CategoryMutation;
use craft\gql\mutations\Entry as EntryMutation;
use craft\gql\mutations\GlobalSet as GlobalSetMutation;
use craft\gql\mutations\Ping as PingMutation;
use craft\gql\mutations\Tag as TagMutation;
use craft\gql\queries\Address as AddressQuery;
use craft\gql\queries\Asset as AssetQuery;
use craft\gql\queries\Category as CategoryQuery;
use craft\gql\queries\Entry as EntryQuery;
use craft\gql\queries\GlobalSet as GlobalSetQuery;
use craft\gql\queries\Ping as PingQuery;
use craft\gql\queries\Tag as TagQuery;
use craft\gql\queries\User as UserQuery;
use craft\gql\TypeLoader;
use craft\gql\TypeManager;
use craft\gql\types\DateTime;
use craft\gql\types\Mutation;
use craft\gql\types\Number;
use craft\gql\types\Query;
use craft\gql\types\QueryArgument;
use craft\helpers\DateTimeHelper;
use craft\helpers\Db;
use craft\helpers\Gql as GqlHelper;
use craft\helpers\ProjectConfig as ProjectConfigHelper;
use craft\helpers\StringHelper;
use craft\models\FieldLayout;
use craft\models\GqlSchema;
use craft\models\GqlToken;
use craft\models\Section;
use craft\records\GqlSchema as GqlSchemaRecord;
use craft\records\GqlToken as GqlTokenRecord;
use GraphQL\Error\DebugFlag;
use GraphQL\Error\Error;
use GraphQL\GraphQL;
use GraphQL\Type\Definition\Directive as GqlDirective;
use GraphQL\Type\Schema;
use GraphQL\Validator\DocumentValidator;
use GraphQL\Validator\Rules\DisableIntrospection;
use GraphQL\Validator\Rules\FieldsOnCorrectType;
use GraphQL\Validator\Rules\KnownTypeNames;
use GraphQL\Validator\Rules\QueryComplexity;
use GraphQL\Validator\Rules\QueryDepth;
use Throwable;
use yii\base\Component;
use yii\base\Exception;
use yii\base\InvalidArgumentException;
use yii\base\UnknownMethodException;
use yii\caching\TagDependency;
/**
* GraphQL service.
*
* An instance of the service is available via [[\craft\base\ApplicationTrait::getGql()|`Craft::$app->gql`]].
*
* @author Pixel & Tonic, Inc. <[email protected]>
* @since 3.3.0
*/
class Gql extends Component
{
/**
* @event RegisterGqlTypesEvent The event that is triggered when registering GraphQL types.
*
* Plugins get a chance to add their own GraphQL types.
* See [GraphQL API](https://craftcms.com/docs/5.x/extend/graphql.html) for documentation on adding GraphQL support.
*
* ---
* ```php
* use craft\events\RegisterGqlTypesEvent;
* use craft\services\Gql;
* use yii\base\Event;
*
* Event::on(Gql::class, Gql::EVENT_REGISTER_GQL_TYPES, function(RegisterGqlTypesEvent $event) {
* // Add my GraphQL types
* $event->types[] = MyType::class;
* });
* ```
*/
public const EVENT_REGISTER_GQL_TYPES = 'registerGqlTypes';
/**
* @event RegisterGqlQueriesEvent The event that is triggered when registering GraphQL queries.
*
* Plugins get a chance to add their own GraphQL queries.
* See [GraphQL API](https://craftcms.com/docs/5.x/extend/graphql.html) for documentation on adding GraphQL support.
*
* ---
* ```php
* use craft\events\RegisterGqlQueriesEvent;
* use craft\services\Gql;
* use yii\base\Event;
* use GraphQL\Type\Definition\Type;
*
* Event::on(Gql::class, Gql::EVENT_REGISTER_GQL_QUERIES, function(RegisterGqlQueriesEvent $event) {
* // Add my GraphQL queries
* $event->queries['queryPluginData'] =
* [
* 'type' => Type::listOf(MyType::getType()),
* 'args' => MyArguments::getArguments(),
* 'resolve' => MyResolver::class . '::resolve'
* ];
* });
* ```
*/
public const EVENT_REGISTER_GQL_QUERIES = 'registerGqlQueries';
/**
* @event RegisterGqlMutationsEvent The event that is triggered when registering GraphQL mutations.
*
* Plugins get a chance to add their own GraphQL mutations.
* See [GraphQL API](https://craftcms.com/docs/5.x/extend/graphql.html) for documentation on adding GraphQL support.
*
* ---
* ```php
* use craft\events\RegisterGqlMutationsEvent;
* use craft\services\Gql;
* use yii\base\Event;
* use GraphQL\Type\Definition\Type;
*
* Event::on(Gql::class, Gql::EVENT_REGISTER_GQL_MUTATIONS, function(RegisterGqlMutationsEvent $event) {
* // Add my GraphQL mutations
* $event->mutations['mutationPluginData'] =
* [
* 'type' => Type::listOf(MyType::getType()),
* 'args' => MyArguments::getArguments(),
* ];
* });
* ```
*/
public const EVENT_REGISTER_GQL_MUTATIONS = 'registerGqlMutations';
/**
* @event RegisterGqlDirectivesEvent The event that is triggered when registering GraphQL directives.
*
* Plugins get a chance to add their own GraphQL directives.
* See [GraphQL API](https://craftcms.com/docs/5.x/extend/graphql.html) for documentation on adding GraphQL support.
*
* ---
* ```php
* use craft\events\RegisterGqlDirectivesEvent;
* use craft\services\Gql;
* use yii\base\Event;
*
* Event::on(Gql::class,
* Gql::EVENT_REGISTER_GQL_DIRECTIVES,
* function(RegisterGqlDirectivesEvent $event) {
* $event->directives[] = MyDirective::class;
* }
* );
* ```
*/
public const EVENT_REGISTER_GQL_DIRECTIVES = 'registerGqlDirectives';
/**
* @event RegisterGqlSchemaComponentsEvent The event that is triggered when registering GraphQL schema components.
* @since 3.5.0
*/
public const EVENT_REGISTER_GQL_SCHEMA_COMPONENTS = 'registerGqlSchemaComponents';
/**
* @event DefineGqlValidationRulesEvent The event that is triggered when defining validation rules to be used.
*
* Plugins get a chance to alter the GraphQL validation rule list.
*
* ---
* ```php
* use craft\events\DefineGqlValidationRulesEvent;
* use craft\services\Gql;
* use yii\base\Event;
* use GraphQL\Type\Definition\Type;
* use GraphQL\Validator\Rules\DisableIntrospection;
*
* Event::on(Gql::class, Gql::::EVENT_DEFINE_GQL_VALIDATION_RULES, function (DefineGqlValidationRulesEvent $event) {
* // Disable introspection permanently.
* $event->validationRules[DisableIntrospection::class] = new DisableIntrospection();
* });
* ```
*/
public const EVENT_DEFINE_GQL_VALIDATION_RULES = 'defineGqlValidationRules';
/**
* @event ExecuteGqlQueryEvent The event that is triggered before executing the GraphQL query.
*
* Plugins get a chance to modify the query or return a cached response.
*
* ---
* ```php
* use craft\events\ExecuteGqlQueryEvent;
* use craft\services\Gql;
* use yii\base\Event;
*
* Event::on(Gql::class,
* Gql::EVENT_BEFORE_EXECUTE_GQL_QUERY,
* function(ExecuteGqlQueryEvent $event) {
* // Set the result from cache
* $event->result = ...;
* }
* );
* ```
*
* @since 3.3.11
*/
public const EVENT_BEFORE_EXECUTE_GQL_QUERY = 'beforeExecuteGqlQuery';
/**
* @event ExecuteGqlQueryEvent The event that is triggered after executing the GraphQL query.
*
* Plugins get a chance to do something after a performed GraphQL query.
*
* ---
* ```php
* use craft\events\ExecuteGqlQueryEvent;
* use craft\services\Gql;
* use yii\base\Event;
*
* Event::on(Gql::class,
* Gql::EVENT_AFTER_EXECUTE_GQL_QUERY,
* function(ExecuteGqlQueryEvent $event) {
* // Cache the results from $event->result or just tweak them
* }
* );
* ```
*
* @since 3.3.11
*/
public const EVENT_AFTER_EXECUTE_GQL_QUERY = 'afterExecuteGqlQuery';
/**
* @since 3.3.12
*/
public const CACHE_TAG = 'graphql';
/**
* The field name to use when fetching count of related elements
*
* @since 3.4.0
*/
public const GRAPHQL_COUNT_FIELD = '_count';
/**
* Complexity value for accessing a simple field.
*
* @since 3.6.0
*/
public const GRAPHQL_COMPLEXITY_SIMPLE_FIELD = 1;
/**
* Complexity value for accessing a field that will trigger a single query for the request.
*
* @since 3.6.0
*/
public const GRAPHQL_COMPLEXITY_QUERY = 10;
/**
* Complexity value for accessing a field that will add an instance of eager-loading for the request.
*
* @since 3.6.0
*/
public const GRAPHQL_COMPLEXITY_EAGER_LOAD = 25;
/**
* Complexity value for accessing a field that will likely trigger a CPU heavy operation.
*
* @since 3.6.0
*/
public const GRAPHQL_COMPLEXITY_CPU_HEAVY = 200;
/**
* Complexity value for accessing a field that will trigger a query for every parent returned.
*
* @since 3.6.0
*/
public const GRAPHQL_COMPLEXITY_NPLUS1 = 500;
/**
* @var Schema|null Currently loaded schema definition
*/
private ?Schema $_schemaDef = null;
/**
* @var GqlSchema|null The active GraphQL schema
* @see setActiveSchema()
*/
private ?GqlSchema $_schema = null;
/**
* @var array Content arguments by element class
* @see getOrSetContentArguments()
*/
private array $_contentArguments = [];
/**
* @var TypeManager|null GQL type manager
*/
private ?TypeManager $_typeManager = null;
/**
* @var array
*/
private array $_typeDefinitions = [];
/**
* @var GqlToken|null
* @see getPublicToken()
*/
private ?GqlToken $_publicToken = null;
/**
* Returns the GraphQL schema.
*
* @param GqlSchema|null $schema
* @param bool $prebuildSchema should the schema be deep-scanned and pre-built instead of lazy-loaded
* @return Schema
* @throws GqlException in case of invalid schema
*/
public function getSchemaDef(?GqlSchema $schema = null, bool $prebuildSchema = false): Schema
{
if ($schema) {
$this->setActiveSchema($schema);
}
if (!$this->_schemaDef || $prebuildSchema) {
// Either cached version was not found or we need a pre-built schema.
$registeredTypes = $this->_registerGqlTypes();
$this->_registerGqlQueries();
$this->_registerGqlMutations();
$schemaConfig = [
'typeLoader' => TypeLoader::class . '::loadType',
'query' => TypeLoader::loadType('Query'),
'mutation' => TypeLoader::loadType('Mutation'),
'directives' => $this->_loadGqlDirectives(),
];
// If we're not required to pre-build the schema the relevant GraphQL types will be added to the Schema
// as the query is being resolved thanks to the magic of lazy-loading, so we needn't worry.
if (!$prebuildSchema) {
$this->_schemaDef = new Schema($schemaConfig);
return $this->_schemaDef;
}
foreach ($registeredTypes as $registeredType) {
if (method_exists($registeredType, 'getTypeGenerator')) {
$typeGeneratorClass = $registeredType::getTypeGenerator();
if (is_subclass_of($typeGeneratorClass, GeneratorInterface::class)) {
foreach ($typeGeneratorClass::generateTypes() as $type) {
$schemaConfig['types'][] = $type;
}
}
}
}
try {
$this->_schemaDef = new Schema($schemaConfig);
$this->_schemaDef->getTypeMap();
} catch (Throwable $exception) {
throw new GqlException('Failed to validate the GQL Schema - ' . $exception->getMessage(), previous: $exception);
}
}
return $this->_schemaDef;
}
/**
* Return a set of validation rules to use.
*
* @param bool $debug Whether debugging validation rules should be allowed.
* @param bool $isIntrospectionQuery Whether this is an introspection query
* @return array
*/
public function getValidationRules(bool $debug = false, bool $isIntrospectionQuery = false): array
{
$validationRules = DocumentValidator::defaultRules();
if (!$debug) {
// Remove the rules which would generate a full schema just for a nice message, to avoid performance hit.
unset(
$validationRules[KnownTypeNames::class],
$validationRules[FieldsOnCorrectType::class]
);
}
$generalConfig = Craft::$app->getConfig()->getGeneral();
if (!$isIntrospectionQuery) {
// Set complexity rule, if defined,
if (!empty($generalConfig->maxGraphqlComplexity)) {
$validationRules[QueryComplexity::class] = new QueryComplexity($generalConfig->maxGraphqlComplexity);
}
// Set depth rule, if defined,
if (!empty($generalConfig->maxGraphqlDepth)) {
$validationRules[QueryDepth::class] = new QueryDepth($generalConfig->maxGraphqlDepth);
}
}
if (!$generalConfig->enableGraphqlIntrospection && Craft::$app->getUser()->getIsGuest()) {
$validationRules[DisableIntrospection::class] = new DisableIntrospection();
}
// Fire a 'defineGqlValidationRules' event
if ($this->hasEventHandlers(self::EVENT_DEFINE_GQL_VALIDATION_RULES)) {
$event = new DefineGqlValidationRulesEvent([
'validationRules' => $validationRules,
'debug' => $debug,
]);
$this->trigger(self::EVENT_DEFINE_GQL_VALIDATION_RULES, $event);
$validationRules = $event->validationRules;
}
return array_values($validationRules);
}
/**
* Execute a GraphQL query for a given schema.
*
* @param GqlSchema $schema The schema definition to use.
* @param string $query The query string to execute.
* @param array|null $variables The variables to use.
* @param string|null $operationName The operation name.
* @param bool $debugMode Whether debug mode validations rules should be used for GraphQL.
* @return array
* @since 3.3.11
*/
public function executeQuery(
GqlSchema $schema,
string $query,
?array $variables = null,
?string $operationName = null,
bool $debugMode = false,
): array {
$context = [
'conditionBuilder' => Craft::createObject([
'class' => ElementQueryConditionBuilder::class,
]),
'argumentManager' => Craft::createObject([
'class' => ArgumentManager::class,
]),
];
// Fire a 'beforeExecuteGqlQuery' event
if ($this->hasEventHandlers(self::EVENT_BEFORE_EXECUTE_GQL_QUERY)) {
$event = new ExecuteGqlQueryEvent([
'schemaId' => $schema->id,
'query' => $query,
'variables' => $variables,
'operationName' => $operationName,
'context' => $context,
]);
$this->trigger(self::EVENT_BEFORE_EXECUTE_GQL_QUERY, $event);
$query = $event->query;
$rootValue = $event->rootValue;
$variables = $event->variables;
$operationName = $event->operationName;
$context = $event->context;
$result = $event->result;
} else {
$result = $rootValue = null;
}
if ($result === null) {
$cacheKey = $this->_getCacheKey(
$schema,
$query,
$rootValue,
$variables,
$operationName,
);
if ($cacheKey && ($cachedResult = $this->getCachedResult($cacheKey)) !== null) {
$result = $cachedResult;
} else {
$isIntrospectionQuery = GqlHelper::isIntrospectionQuery($query);
$prebuildSchema = $isIntrospectionQuery || !Craft::$app->getConfig()->getGeneral()->lazyGqlTypes;
$schemaDef = $this->getSchemaDef($schema, $prebuildSchema);
$elementsService = Craft::$app->getElements();
$elementsService->startCollectingCacheInfo();
$result = GraphQL::executeQuery(
$schemaDef,
$query,
$rootValue,
$context,
$variables,
$operationName,
null,
$this->getValidationRules($debugMode, $isIntrospectionQuery)
)
->setErrorsHandler([$this, 'handleQueryErrors'])
->toArray($debugMode ? DebugFlag::INCLUDE_DEBUG_MESSAGE | DebugFlag::INCLUDE_TRACE : false);
[$dep, $duration] = $elementsService->stopCollectingCacheInfo();
if (empty($result['errors']) && $cacheKey) {
$this->setCachedResult($cacheKey, $result, $dep, $duration);
}
}
}
// Fire an 'afterExecuteGqlQuery' event
if ($this->hasEventHandlers(self::EVENT_AFTER_EXECUTE_GQL_QUERY)) {
$event = new ExecuteGqlQueryEvent([
'schemaId' => $schema->id,
'query' => $query,
'variables' => $variables,
'operationName' => $operationName,
'context' => $context,
'rootValue' => $rootValue,
'result' => $result,
]);
$this->trigger(self::EVENT_AFTER_EXECUTE_GQL_QUERY, $event);
$result = $event->result;
}
return $result ?? [];
}
/**
* Invalidates all GraphQL result caches.
*
* @since 3.3.12
*/
public function invalidateCaches(): void
{
TagDependency::invalidate(Craft::$app->getCache(), self::CACHE_TAG);
}
/**
* Returns the cached result for a key.
*
* @param string $cacheKey
* @return array|null
* @since 3.3.12
*/
public function getCachedResult(string $cacheKey): ?array
{
return Craft::$app->getCache()->get($cacheKey) ?: null;
}
/**
* Cache a result for the key and tag it.
*
* @param string $cacheKey
* @param array $result
* @param TagDependency|null $dependency
* @param int|null $duration
* @since 3.3.12
*/
public function setCachedResult(string $cacheKey, array $result, ?TagDependency $dependency = null, ?int $duration = null): void
{
if ($dependency === null) {
$dependency = new TagDependency();
}
// Add the global graphql cache tag
$dependency->tags[] = self::CACHE_TAG;
Craft::$app->getCache()->set($cacheKey, $result, $duration, $dependency);
}
/**
* Returns the active GraphQL schema.
*
* @return GqlSchema
* @throws GqlException if no schema is currently active.
*/
public function getActiveSchema(): GqlSchema
{
if (!$this->_schema) {
throw new GqlException('No schema is active.');
}
return $this->_schema;
}
/**
* Sets the active GraphQL schema.
*
* @param GqlSchema|null $schema The schema, or `null` to unset the active schema
* @throws Exception
*/
public function setActiveSchema(?GqlSchema $schema = null): void
{
$this->_schema = $schema;
}
/**
* Returns all GraphQL tokens.
*
* @return GqlToken[]
* @since 3.4.0
*/
public function getTokens(): array
{
$rows = $this->_createTokenQuery()->all();
$schemas = [];
$names = [];
foreach ($rows as $row) {
$token = new GqlToken($row);
if (!$token->getIsPublic()) {
$schemas[] = $token;
$names[] = $token->name;
}
}
// Sort them by name
array_multisort($names, SORT_ASC, SORT_STRING, $schemas);
return $schemas;
}
/**
* Returns the public schema. If it does not exist and admin changes are allowed, it will be created.
*
* @return GqlSchema|null
* @throws Exception
*/
public function getPublicSchema(): ?GqlSchema
{
return $this->getPublicToken()?->getSchema();
}
/**
* Returns all of the known GraphQL schema components.
*
* @return array
* @since 3.5.0
*/
public function getAllSchemaComponents(): array
{
$queries = [];
$mutations = [];
// Sites
$label = Craft::t('app', 'Sites');
[$queries[$label], $mutations[$label]] = $this->siteSchemaComponents();
// Elements
$label = Craft::t('app', 'All elements');
[$queries[$label], $mutations[$label]] = $this->elementSchemaComponents();
// Entries
$label = Craft::t('app', 'Entries');
[$queries[$label], $mutations[$label]] = $this->entrySchemaComponents();
// Assets
$label = Craft::t('app', 'Assets');
[$queries[$label], $mutations[$label]] = $this->assetSchemaComponents();
// Global Sets
$label = Craft::t('app', 'Global Sets');
[$queries[$label], $mutations[$label]] = $this->globalSetSchemaComponents();
// Users
$label = Craft::t('app', 'Users');
[$queries[$label], $mutations[$label]] = $this->userSchemaComponents();
// Categories
$label = Craft::t('app', 'Categories');
[$queries[$label], $mutations[$label]] = $this->categorySchemaComponents();
// Tags
$label = Craft::t('app', 'Tags');
[$queries[$label], $mutations[$label]] = $this->tagSchemaComponents();
// Fire a 'registerGqlSchemaComponents' event
if ($this->hasEventHandlers(self::EVENT_REGISTER_GQL_SCHEMA_COMPONENTS)) {
$event = new RegisterGqlSchemaComponentsEvent([
'queries' => $queries,
'mutations' => $mutations,
]);
$this->trigger(self::EVENT_REGISTER_GQL_SCHEMA_COMPONENTS, $event);
$queries = $event->queries;
$mutations = $event->mutations;
}
return [
'queries' => $queries,
'mutations' => $mutations,
];
}
/**
* Flush all GraphQL caches, registries and loaders.
*/
public function flushCaches(): void
{
$this->_schema = null;
$this->_schemaDef = null;
$this->_contentArguments = [];
$this->_typeDefinitions = [];
TypeLoader::flush();
GqlEntityRegistry::flush();
$this->invalidateCaches();
}
/**
* Returns a GraphQL token by its ID.
*
* @param int $id
* @return GqlToken|null
* @since 3.4.0
*/
public function getTokenById(int $id): ?GqlToken
{
$result = $this->_createTokenQuery()
->where(['id' => $id])
->one();
return $result ? new GqlToken($result) : null;
}
/**
* Returns a GraphQL token by its name.
*
* @param string $tokenName
* @return GqlToken|null
* @since 3.4.0
*/
public function getTokenByName(string $tokenName): ?GqlToken
{
$result = $this->_createTokenQuery()
->where(['name' => $tokenName])
->one();
return $result ? new GqlToken($result) : null;
}
/**
* Returns a GraphQL token by its UID.
*
* @param string $uid
* @return GqlToken
* @throws InvalidArgumentException if $uid is invalid
* @since 3.4.0
*/
public function getTokenByUid(string $uid): GqlToken
{
$result = $this->_createTokenQuery()
->where(['uid' => $uid])
->one();
if (!$result) {
throw new InvalidArgumentException('Invalid UID');
}
return new GqlToken($result);
}
/**
* Returns a GraphQL token by its access token.
*
* @param string $token
* @return GqlToken
* @throws InvalidArgumentException if $token is invalid
* @since 3.4.0
*/
public function getTokenByAccessToken(string $token): GqlToken
{
if ($token === GqlToken::PUBLIC_TOKEN) {
$publicToken = $this->getPublicToken();
if (!$publicToken) {
throw new InvalidArgumentException('Invalid access token');
}
return $publicToken;
}
$result = $this->_createTokenQuery()
->where(['accessToken' => $token])
->one();
if (!$result) {
throw new InvalidArgumentException('Invalid access token');
}
return new GqlToken($result);
}
/**
* Returns the public token. If it does not exist and admin changes are allowed, it will be created.
*
* @return GqlToken|null
* @since 3.5.0
*/
public function getPublicToken(): ?GqlToken
{
if (!isset($this->_publicToken)) {
$config = Craft::$app->getProjectConfig()->get(ProjectConfig::PATH_GRAPHQL_PUBLIC_TOKEN) ?? [];
$this->_publicToken = $this->_createPublicToken($config);
if ($this->_publicToken) {
$this->_publicToken->id = $this->_createTokenQuery()
->select(['id'])
->where(['accessToken' => GqlToken::PUBLIC_TOKEN])
->scalar();
}
}
return $this->_publicToken;
}
/**
* Creates a public token with the given config.
*
* @param array $config
* @return GqlToken|null
*/
private function _createPublicToken(array $config): ?GqlToken
{
$schema = $this->_getPublicSchema();
if (!$schema) {
if (!Craft::$app->getConfig()->getGeneral()->allowAdminChanges) {
return null;
}
$schema = $this->_createPublicSchema();
}
return new GqlToken([
'name' => 'Public Token',
'accessToken' => GqlToken::PUBLIC_TOKEN,
'schema' => $schema,
'enabled' => $config['enabled'] ?? false,
'expiryDate' => DateTimeHelper::toDateTime($config['expiryDate'] ?? false) ?: null,
]);
}
/**
* Saves a GraphQL token.
*
* @param GqlToken $token the schema to save
* @param bool $runValidation Whether the schema should be validated
* @return bool Whether the schema was saved successfully
* @throws Exception
* @since 3.4.0
*/
public function saveToken(GqlToken $token, bool $runValidation = true): bool
{
if ($token->isTemporary) {
return false;
}
if ($runValidation && !$token->validate()) {
Craft::info('Token not saved due to validation error.', __METHOD__);
return false;
}
// Public token information is stored in the project config
if ($token->accessToken === GqlToken::PUBLIC_TOKEN) {
$data = [
'enabled' => $token->enabled,
'expiryDate' => $token->expiryDate?->getTimestamp(),
];
$projectConfigService = Craft::$app->getProjectConfig();
$muteEvents = $projectConfigService->muteEvents;
$projectConfigService->muteEvents = false;
Craft::$app->getProjectConfig()->set(ProjectConfig::PATH_GRAPHQL_PUBLIC_TOKEN, $data);
$projectConfigService->muteEvents = $muteEvents;
}
$this->_saveTokenInternal($token);
return true;
}
/**
* Handle public token settings being updated.
*
* @param ConfigEvent $event
* @since 3.5.0
*/
public function handleChangedPublicToken(ConfigEvent $event): void
{
// If we're just adding a public schema, ensure it makes it in.
ProjectConfigHelper::ensureAllGqlSchemasProcessed();
$this->_publicToken = $this->_createPublicToken($event->newValue);
}
/**
* Deletes a GraphQL token by its ID.
*
* @param int $id The schemas's ID
* @return bool Whether the schema was deleted.
* @since 3.4.0
*/
public function deleteTokenById(int $id): bool
{
$record = GqlTokenRecord::findOne($id);
if (!$record) {
return true;
}
return $record->delete();
}
/**
* Saves a GraphQL schema.
*
* @param GqlSchema $schema the schema to save
* @param bool $runValidation Whether the schema should be validated
* @return bool Whether the schema was saved successfully
* @throws Exception
* @since 3.4.0
*/
public function saveSchema(GqlSchema $schema, bool $runValidation = true): bool
{
$isNewSchema = !$schema->id;
if ($runValidation && !$schema->validate()) {
Craft::info('Schema not saved due to validation error.', __METHOD__);
return false;
}
if ($isNewSchema && empty($schema->uid)) {
$schema->uid = StringHelper::UUID();
} elseif (empty($schema->uid)) {
$schema->uid = Db::uidById(Table::GQLSCHEMAS, $schema->id);
}
$configPath = ProjectConfig::PATH_GRAPHQL_SCHEMAS . '.' . $schema->uid;
$configData = $schema->getConfig();
Craft::$app->getProjectConfig()->set($configPath, $configData, "Save GraphQL schema “{$schema->name}”");
if ($isNewSchema) {
$schema->id = Db::idByUid(Table::GQLSCHEMAS, $schema->uid);
}
return true;
}
/**
* Handle schema change
*
* @param ConfigEvent $event
* @since 3.4.0
*/
public function handleChangedSchema(ConfigEvent $event): void
{
$schemaUid = $event->tokenMatches[0];
$data = $event->newValue;
$transaction = Craft::$app->getDb()->beginTransaction();
try {
$schemaRecord = $this->_getSchemaRecord($schemaUid);