/
AbstractDirectiveResolver.php
executable file
·911 lines (859 loc) · 38.7 KB
/
AbstractDirectiveResolver.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
<?php
declare(strict_types=1);
namespace PoP\ComponentModel\DirectiveResolvers;
use Composer\Semver\Semver;
use Exception;
use League\Pipeline\StageInterface;
use PoP\ComponentModel\AttachableExtensions\AttachableExtensionTrait;
use PoP\ComponentModel\DirectivePipeline\DirectivePipelineUtils;
use PoP\ComponentModel\Directives\DirectiveTypes;
use PoP\ComponentModel\Environment;
use PoP\ComponentModel\Facades\Schema\FieldQueryInterpreterFacade;
use PoP\ComponentModel\Feedback\Tokens;
use PoP\ComponentModel\Resolvers\FieldOrDirectiveResolverTrait;
use PoP\ComponentModel\Resolvers\ResolverTypes;
use PoP\ComponentModel\Schema\SchemaDefinition;
use PoP\ComponentModel\State\ApplicationState;
use PoP\ComponentModel\TypeResolvers\FieldSymbols;
use PoP\ComponentModel\TypeResolvers\PipelinePositions;
use PoP\ComponentModel\TypeResolvers\TypeResolverInterface;
use PoP\ComponentModel\Versioning\VersioningHelpers;
use PoP\FieldQuery\QueryHelpers;
use PoP\Translation\Facades\TranslationAPIFacade;
abstract class AbstractDirectiveResolver implements DirectiveResolverInterface, SchemaDirectiveResolverInterface, StageInterface
{
use AttachableExtensionTrait;
use RemoveIDsDataFieldsDirectiveResolverTrait;
use FieldOrDirectiveResolverTrait;
const MESSAGE_EXPRESSIONS = 'expressions';
protected string $directive;
/**
* @var array<string, array>
*/
protected array $directiveArgsForSchema = [];
/**
* @var array<string, array>
*/
protected array $directiveArgsForResultItems = [];
/**
* @var array[]
*/
protected array $nestedDirectivePipelineData = [];
/**
* The directiveResolvers are NOT instantiated through the service container!
* Instead, the directive will be instantiated in AbstractTypeResolver:
* new $directiveClass($fieldDirective)
* Then, the constructor is made final, to avoid creating inheriting classes
* whose properties are expected to be injected via dependency injection.
*
* Whenever having depended-upon services,
* these must be obtained from the container by doing:
* $instanceManager->getInstance(...)
*
* DirectiveResolvers must still be added to schema-services.yml, though.
* This is because they need to be registered, so that all directives
* can be displayed in the GraphQL API's Access Control Lists
*/
final public function __construct(?string $directive = null)
{
// If the directive is not provided, then it directly the directive name
// This allows to instantiate the directive through the DependencyInjection component
$this->directive = $directive ?? $this->getDirectiveName();
}
/**
* Directives can be either of type "Schema" or "Query" and,
* depending on one case or the other, might be exposed to the user.
* By default, use the Query type
*/
public function getDirectiveType(): string
{
return DirectiveTypes::QUERY;
}
/**
* If a directive does not operate over the resultItems, then it must not allow to add fields or dynamic values in the directive arguments
* Otherwise, it can lead to errors, since the field would never be transformed/casted to the expected type
* Eg: <cacheControl(maxAge:id())>
*/
protected function disableDynamicFieldsFromDirectiveArgs(): bool
{
return false;
}
public function dissectAndValidateDirectiveForSchema(
TypeResolverInterface $typeResolver,
array &$fieldDirectiveFields,
array &$variables,
array &$schemaErrors,
array &$schemaWarnings,
array &$schemaDeprecations,
array &$schemaNotices,
array &$schemaTraces
): array {
$translationAPI = TranslationAPIFacade::getInstance();
$fieldQueryInterpreter = FieldQueryInterpreterFacade::getInstance();
// If it has nestedDirectives, extract them and validate them
$nestedFieldDirectives = $fieldQueryInterpreter->getFieldDirectives($this->directive, false);
if ($nestedFieldDirectives) {
$nestedDirectiveSchemaErrors = $nestedDirectiveSchemaWarnings = $nestedDirectiveSchemaDeprecations = $nestedDirectiveSchemaNotices = $nestedDirectiveSchemaTraces = [];
$nestedFieldDirectives = QueryHelpers::splitFieldDirectives($nestedFieldDirectives);
// Support repeated fields by adding a counter next to them
if (count($nestedFieldDirectives) != count(array_unique($nestedFieldDirectives))) {
// Find the repeated fields, and add a counter next to them
$expandedNestedFieldDirectives = [];
$counters = [];
foreach ($nestedFieldDirectives as $nestedFieldDirective) {
if (!isset($counters[$nestedFieldDirective])) {
$expandedNestedFieldDirectives[] = $nestedFieldDirective;
$counters[$nestedFieldDirective] = 1;
} else {
$expandedNestedFieldDirectives[] = $nestedFieldDirective . FieldSymbols::REPEATED_DIRECTIVE_COUNTER_SEPARATOR . $counters[$nestedFieldDirective];
$counters[$nestedFieldDirective]++;
}
}
$nestedFieldDirectives = $expandedNestedFieldDirectives;
}
// Each composed directive will deal with the same fields as the current directive
$nestedFieldDirectiveFields = $fieldDirectiveFields;
foreach ($nestedFieldDirectives as $nestedFieldDirective) {
$nestedFieldDirectiveFields[$nestedFieldDirective] = $fieldDirectiveFields[$this->directive];
}
$this->nestedDirectivePipelineData = $typeResolver->resolveDirectivesIntoPipelineData(
$nestedFieldDirectives,
$nestedFieldDirectiveFields,
true,
$variables,
$nestedDirectiveSchemaErrors,
$nestedDirectiveSchemaWarnings,
$nestedDirectiveSchemaDeprecations,
$nestedDirectiveSchemaNotices,
$nestedDirectiveSchemaTraces
);
foreach ($nestedDirectiveSchemaDeprecations as $nestedDirectiveSchemaDeprecation) {
$schemaDeprecations[] = [
Tokens::PATH => array_merge([$this->directive], $nestedDirectiveSchemaDeprecation[Tokens::PATH]),
Tokens::MESSAGE => $nestedDirectiveSchemaDeprecation[Tokens::MESSAGE],
];
}
foreach ($nestedDirectiveSchemaWarnings as $nestedDirectiveSchemaWarning) {
$schemaWarnings[] = [
Tokens::PATH => array_merge([$this->directive], $nestedDirectiveSchemaWarning[Tokens::PATH]),
Tokens::MESSAGE => $nestedDirectiveSchemaWarning[Tokens::MESSAGE],
];
}
foreach ($nestedDirectiveSchemaNotices as $nestedDirectiveSchemaNotice) {
$schemaNotices[] = [
Tokens::PATH => array_merge([$this->directive], $nestedDirectiveSchemaNotice[Tokens::PATH]),
Tokens::MESSAGE => $nestedDirectiveSchemaNotice[Tokens::MESSAGE],
];
}
foreach ($nestedDirectiveSchemaTraces as $nestedDirectiveSchemaTrace) {
$schemaTraces[] = [
Tokens::PATH => array_merge([$this->directive], $nestedDirectiveSchemaTrace[Tokens::PATH]),
Tokens::MESSAGE => $nestedDirectiveSchemaTrace[Tokens::MESSAGE],
];
}
// If there is any error, then we also can't proceed with the current directive
if ($nestedDirectiveSchemaErrors) {
foreach ($nestedDirectiveSchemaErrors as $nestedDirectiveSchemaError) {
$schemaErrors[] = [
Tokens::PATH => array_merge([$this->directive], $nestedDirectiveSchemaError[Tokens::PATH]),
Tokens::MESSAGE => $nestedDirectiveSchemaError[Tokens::MESSAGE],
];
}
$schemaErrors[] = [
Tokens::PATH => [$this->directive],
Tokens::MESSAGE => $translationAPI->__('This directive can\'t be executed due to errors from its composed directives', 'component-model'),
];
return [
null, // $validDirective
// null, // $directiveName <= null because no need to find out which one it is
// null, // $directiveArgs <= null because no need to find out which one it is
];
}
}
// First validate schema (eg of error in schema: ?query=posts<include(if:this-field-doesnt-exist())>)
list(
$validDirective,
$directiveName,
$directiveArgs,
$directiveSchemaErrors,
$directiveSchemaWarnings,
$directiveSchemaDeprecations
) = $fieldQueryInterpreter->extractDirectiveArgumentsForSchema(
$this,
$typeResolver,
$this->directive,
$variables,
$this->disableDynamicFieldsFromDirectiveArgs()
);
// Store the args, they may be used in `resolveDirective`
$this->directiveArgsForSchema = $directiveArgs;
// If there were errors, warning or deprecations, integrate them into the feedback objects
$schemaErrors = array_merge(
$schemaErrors,
$directiveSchemaErrors
);
// foreach ($directiveSchemaErrors as $directiveSchemaError) {
// $schemaErrors[] = [
// Tokens::PATH => array_merge([$this->directive], $directiveSchemaError[Tokens::PATH]),
// Tokens::MESSAGE => $directiveSchemaError[Tokens::MESSAGE],
// ];
// }
$schemaWarnings = array_merge(
$schemaWarnings,
$directiveSchemaWarnings
);
// foreach ($directiveSchemaWarnings as $directiveSchemaWarning) {
// $schemaWarnings[] = [
// Tokens::PATH => array_merge([$this->directive], $directiveSchemaWarning[Tokens::PATH]),
// Tokens::MESSAGE => $directiveSchemaWarning[Tokens::MESSAGE],
// ];
// }
$schemaDeprecations = array_merge(
$schemaDeprecations,
$directiveSchemaDeprecations
);
// foreach ($directiveSchemaDeprecations as $directiveSchemaDeprecation) {
// $schemaDeprecations[] = [
// Tokens::PATH => array_merge([$this->directive], $directiveSchemaDeprecation[Tokens::PATH]),
// Tokens::MESSAGE => $directiveSchemaDeprecation[Tokens::MESSAGE],
// ];
// }
return [
$validDirective,
$directiveName,
$directiveArgs,
];
}
/**
* By default, validate if there are deprecated fields
*/
public function validateDirectiveArgumentsForSchema(TypeResolverInterface $typeResolver, string $directiveName, array $directiveArgs, array &$schemaErrors, array &$schemaWarnings, array &$schemaDeprecations): array
{
if (
$maybeDeprecation = $this->resolveSchemaDirectiveDeprecationDescription(
$typeResolver,
$directiveName,
$directiveArgs
)
) {
$schemaDeprecations[] = [
Tokens::PATH => [$this->directive],
Tokens::MESSAGE => $maybeDeprecation,
];
}
return $directiveArgs;
}
public function dissectAndValidateDirectiveForResultItem(
TypeResolverInterface $typeResolver,
object $resultItem,
array &$variables,
array &$expressions,
array &$dbErrors,
array &$dbWarnings,
array &$dbDeprecations
): array {
$fieldQueryInterpreter = FieldQueryInterpreterFacade::getInstance();
list(
$validDirective,
$directiveName,
$directiveArgs,
$nestedDBErrors,
$nestedDBWarnings
) = $fieldQueryInterpreter->extractDirectiveArgumentsForResultItem($this, $typeResolver, $resultItem, $this->directive, $variables, $expressions);
// Store the args, they may be used in `resolveDirective`
$this->directiveArgsForResultItems[$typeResolver->getID($resultItem)] = $directiveArgs;
if ($nestedDBWarnings || $nestedDBErrors) {
foreach ($nestedDBErrors as $id => $fieldOutputKeyErrorMessages) {
$dbErrors[$id] = array_merge(
$dbErrors[$id] ?? [],
$fieldOutputKeyErrorMessages
);
}
foreach ($nestedDBWarnings as $id => $fieldOutputKeyWarningMessages) {
$dbWarnings[$id] = array_merge(
$dbWarnings[$id] ?? [],
$fieldOutputKeyWarningMessages
);
}
}
return [
$validDirective,
$directiveName,
$directiveArgs,
];
}
/**
* Indicate to what fieldNames this directive can be applied.
* Returning an empty array means all of them
*/
public function getFieldNamesToApplyTo(): array
{
// By default, apply to all fieldNames
return [];
}
/**
* Define if to use the version to decide if to process the directive or not
*/
public function decideCanProcessBasedOnVersionConstraint(TypeResolverInterface $typeResolver): bool
{
return false;
}
/**
* By default, the directiveResolver instance can process the directive
* This function can be overriden to force certain value on the directive args before it can be executed
*/
public function resolveCanProcess(TypeResolverInterface $typeResolver, string $directiveName, array $directiveArgs, string $field, array &$variables): bool
{
/** Check if to validate the version */
if (
Environment::enableSemanticVersionConstraints() &&
$this->decideCanProcessBasedOnVersionConstraint($typeResolver)
) {
/**
* Please notice: we can get the fieldVersion directly from this instance,
* and not from the schemaDefinition, because the version is set at the FieldResolver level,
* and not the FieldInterfaceResolver, which is the other entity filling data
* inside the schemaDefinition object.
* If this directive is tagged with a version...
*/
if ($schemaDirectiveVersion = $this->getSchemaDirectiveVersion($typeResolver)) {
$vars = ApplicationState::getVars();
/**
* Get versionConstraint in this order:
* 1. Passed as directive argument
* 2. Through param `directiveVersionConstraints[$directiveName]`: specific to the directive
* 3. Through param `versionConstraint`: applies to all fields and directives in the query
*/
$versionConstraint =
$directiveArgs[SchemaDefinition::ARGNAME_VERSION_CONSTRAINT]
?? VersioningHelpers::getVersionConstraintsForDirective($this->getDirectiveName())
?? $vars['version-constraint'];
/**
* If the query doesn't restrict the version, then do not process
*/
if (!$versionConstraint) {
return false;
}
/**
* Compare using semantic versioning constraint rules, as used by Composer
* If passing a wrong value to validate against (eg: "saraza" instead of "1.0.0"), it will throw an Exception
*/
try {
return Semver::satisfies($schemaDirectiveVersion, $versionConstraint);
} catch (Exception) {
return false;
}
}
}
return true;
}
public function resolveSchemaValidationErrorDescriptions(TypeResolverInterface $typeResolver, string $directiveName, array $directiveArgs = []): ?array
{
$directiveSchemaDefinition = $this->getSchemaDefinitionForDirective($typeResolver);
if ($schemaDirectiveArgs = $directiveSchemaDefinition[SchemaDefinition::ARGNAME_ARGS] ?? null) {
/**
* Validate mandatory values
*/
if (
$maybeError = $this->maybeValidateNotMissingFieldOrDirectiveArguments(
$typeResolver,
$directiveName,
$directiveArgs,
$schemaDirectiveArgs,
ResolverTypes::DIRECTIVE
)
) {
return [$maybeError];
}
/**
* Validate enums
*/
list(
$maybeError
) = $this->maybeValidateEnumFieldOrDirectiveArguments(
$typeResolver,
$directiveName,
$directiveArgs,
$schemaDirectiveArgs,
ResolverTypes::DIRECTIVE
);
if ($maybeError) {
return [$maybeError];
}
}
return null;
}
/**
* @return mixed[]
*/
protected function getExpressionsForResultItem(int | string $id, array &$variables, array &$messages): array
{
// Create a custom $variables containing all the properties from $dbItems for this resultItem
// This way, when encountering $propName in a fieldArg in a fieldResolver, it can resolve that value
// Otherwise it can't, since the fieldResolver doesn't have access to either $dbItems
return array_merge(
$variables,
$messages[self::MESSAGE_EXPRESSIONS][(string)$id] ?? []
);
}
protected function addExpressionForResultItem(int | string $id, string $key, mixed $value, array &$messages): void
{
$messages[self::MESSAGE_EXPRESSIONS][(string)$id][$key] = $value;
}
protected function getExpressionForResultItem(int | string $id, string $key, array &$messages): mixed
{
return $messages[self::MESSAGE_EXPRESSIONS][(string)$id][$key] ?? null;
}
/**
* By default, place the directive after the ResolveAndMerge directive, so the property will be in $dbItems by then
*/
public function getPipelinePosition(): string
{
return PipelinePositions::AFTER_RESOLVE;
}
/**
* By default, a directive can be executed only one time for "Schema" and "System"
* type directives (eg: <translate(en,es),translate(es,en)>),
* and many times for the other types, "Query" and "Scripting"
*/
public function isRepeatable(): bool
{
return !($this->getDirectiveType() == DirectiveTypes::SYSTEM || $this->getDirectiveType() == DirectiveTypes::SCHEMA);
}
/**
* Indicate if the directive needs to be passed $idsDataFields filled with data to be able to execute
* Because most commonly it will need, the default value is `true`
*/
public function needsIDsDataFieldsToExecute(): bool
{
return true;
}
/**
* Indicate that there is data in variable $idsDataFields
*/
protected function hasIDsDataFields(array &$idsDataFields): bool
{
foreach ($idsDataFields as $id => &$data_fields) {
if ($data_fields['direct'] ?? null) {
// If there's data-fields to fetch for any ID, that's it, there's data
return true;
}
}
// If we reached here, there is no data
return false;
}
public function getSchemaDirectiveVersion(TypeResolverInterface $typeResolver): ?string
{
return null;
}
public function enableOrderedSchemaDirectiveArgs(TypeResolverInterface $typeResolver): bool
{
if ($schemaDefinitionResolver = $this->getSchemaDefinitionResolver($typeResolver)) {
return $schemaDefinitionResolver->enableOrderedSchemaDirectiveArgs($typeResolver);
}
return true;
}
public function getSchemaDirectiveArgs(TypeResolverInterface $typeResolver): array
{
if ($schemaDefinitionResolver = $this->getSchemaDefinitionResolver($typeResolver)) {
return $schemaDefinitionResolver->getSchemaDirectiveArgs($typeResolver);
}
return [];
}
public function getFilteredSchemaDirectiveArgs(TypeResolverInterface $typeResolver): array
{
if ($schemaDefinitionResolver = $this->getSchemaDefinitionResolver($typeResolver)) {
$schemaDirectiveArgs = $schemaDefinitionResolver->getSchemaDirectiveArgs($typeResolver);
} else {
$schemaDirectiveArgs = [];
}
$this->maybeAddVersionConstraintSchemaFieldOrDirectiveArg(
$schemaDirectiveArgs,
!empty($this->getSchemaDirectiveVersion($typeResolver))
);
return $schemaDirectiveArgs;
}
public function getSchemaDirectiveDeprecationDescription(TypeResolverInterface $typeResolver): ?string
{
return $this->getSchemaDefinitionResolver($typeResolver)?->getSchemaDirectiveDeprecationDescription($typeResolver);
}
public function resolveSchemaDirectiveDeprecationDescription(TypeResolverInterface $typeResolver, string $directiveName, array $directiveArgs = []): ?string
{
$directiveSchemaDefinition = $this->getSchemaDefinitionForDirective($typeResolver);
if ($schemaDirectiveArgs = $directiveSchemaDefinition[SchemaDefinition::ARGNAME_ARGS] ?? null) {
list(
$maybeError,
$maybeDeprecation
) = $this->maybeValidateEnumFieldOrDirectiveArguments(
$typeResolver,
$directiveName,
$directiveArgs,
$schemaDirectiveArgs,
ResolverTypes::DIRECTIVE
);
if ($maybeDeprecation) {
return $maybeDeprecation;
}
}
return null;
}
public function getSchemaDirectiveWarningDescription(TypeResolverInterface $typeResolver): ?string
{
if ($schemaDefinitionResolver = $this->getSchemaDefinitionResolver($typeResolver)) {
return $schemaDefinitionResolver->getSchemaDirectiveWarningDescription($typeResolver);
}
return null;
}
public function resolveSchemaDirectiveWarningDescription(TypeResolverInterface $typeResolver): ?string
{
if (Environment::enableSemanticVersionConstraints()) {
/**
* If restricting the version, and this fieldResolver doesn't have any version, then show a warning
*/
if ($versionConstraint = $this->directiveArgsForSchema[SchemaDefinition::ARGNAME_VERSION_CONSTRAINT] ?? null) {
/**
* If this fieldResolver doesn't have versioning, then it accepts everything
*/
if (!$this->decideCanProcessBasedOnVersionConstraint($typeResolver)) {
$translationAPI = TranslationAPIFacade::getInstance();
return sprintf(
$translationAPI->__('The DirectiveResolver used to process directive \'%s\' (which has version \'%s\') does not pay attention to the version constraint; hence, argument \'versionConstraint\', with value \'%s\', was ignored', 'component-model'),
$this->getDirectiveName(),
$this->getSchemaDirectiveVersion($typeResolver) ?? '',
$versionConstraint
);
}
}
}
return $this->getSchemaDirectiveWarningDescription($typeResolver);
}
public function getSchemaDirectiveExpressions(TypeResolverInterface $typeResolver): array
{
if ($schemaDefinitionResolver = $this->getSchemaDefinitionResolver($typeResolver)) {
return $schemaDefinitionResolver->getSchemaDirectiveExpressions($typeResolver);
}
return [];
}
public function getSchemaDirectiveDescription(TypeResolverInterface $typeResolver): ?string
{
if ($schemaDefinitionResolver = $this->getSchemaDefinitionResolver($typeResolver)) {
return $schemaDefinitionResolver->getSchemaDirectiveDescription($typeResolver);
}
return null;
}
public function isGlobal(TypeResolverInterface $typeResolver): bool
{
if ($schemaDefinitionResolver = $this->getSchemaDefinitionResolver($typeResolver)) {
return $schemaDefinitionResolver->isGlobal($typeResolver);
}
return false;
}
public function __invoke($payload)
{
// 1. Extract the arguments from the payload
// $pipelineIDsDataFields is an array containing all stages of the pipe
// The one corresponding to the current stage is at the head. Take it out from there,
// and keep passing down the rest of the array to the next stages
list(
$typeResolver,
$pipelineIDsDataFields,
$pipelineDirectiveResolverInstances,
$resultIDItems,
$unionDBKeyIDs,
$dbItems,
$previousDBItems,
$variables,
$messages,
$dbErrors,
$dbWarnings,
$dbDeprecations,
$dbNotices,
$dbTraces,
$schemaErrors,
$schemaWarnings,
$schemaDeprecations,
$schemaNotices,
$schemaTraces
) = DirectivePipelineUtils::extractArgumentsFromPayload($payload);
// Extract the head, keep passing down the rest
$idsDataFields = $pipelineIDsDataFields[0];
array_shift($pipelineIDsDataFields);
// The $pipelineDirectiveResolverInstances is the series of directives executed in the pipeline
// The current stage is at the head. Remove it
array_shift($pipelineDirectiveResolverInstances);
// // 2. Validate operation
// $this->validateDirective(
// $typeResolver,
// $idsDataFields,
// $pipelineIDsDataFields,
// $pipelineDirectiveResolverInstances,
// $resultIDItems,
// $dbItems,
// $previousDBItems,
// $variables,
// $messages,
// $dbErrors,
// $dbWarnings,
// $dbDeprecations,
// $dbNotices,
// $dbTraces,
// $schemaErrors,
// $schemaWarnings,
// $schemaDeprecations,
// $schemaNotices,
// $schemaTraces
// );
// 2. Execute operation.
// First check that if the validation took away the elements, and so the directive can't execute anymore
// For instance, executing ?query=posts.id|title<default,translate(from:en,to:es)> will fail
// after directive "default", so directive "translate" must not even execute
if (!$this->needsIDsDataFieldsToExecute() || $this->hasIDsDataFields($idsDataFields)) {
$this->resolveDirective(
$typeResolver,
$idsDataFields,
$pipelineIDsDataFields,
$pipelineDirectiveResolverInstances,
$resultIDItems,
$unionDBKeyIDs,
$dbItems,
$previousDBItems,
$variables,
$messages,
$dbErrors,
$dbWarnings,
$dbDeprecations,
$dbNotices,
$dbTraces,
$schemaErrors,
$schemaWarnings,
$schemaDeprecations,
$schemaNotices,
$schemaTraces
);
}
// 3. Re-create the payload from the modified variables
return DirectivePipelineUtils::convertArgumentsToPayload(
$typeResolver,
$pipelineIDsDataFields,
$pipelineDirectiveResolverInstances,
$resultIDItems,
$unionDBKeyIDs,
$dbItems,
$previousDBItems,
$variables,
$messages,
$dbErrors,
$dbWarnings,
$dbDeprecations,
$dbNotices,
$dbTraces,
$schemaErrors,
$schemaWarnings,
$schemaDeprecations,
$schemaNotices,
$schemaTraces
);
}
// public function validateDirective(TypeResolverInterface $typeResolver, array &$idsDataFields, array &$succeedingPipelineIDsDataFields, array &$resultIDItems, array &$dbItems, array &$previousDBItems, array &$variables, array &$messages, array &$dbErrors, array &$dbWarnings, array &$dbDeprecations, array &$schemaErrors, array &$schemaWarnings, array &$schemaDeprecations)
// {
// // Check that the directive can be applied to all provided fields
// $this->validateAndFilterFieldsForDirective($idsDataFields, $schemaErrors, $schemaWarnings);
// }
// /**
// * Check that the directive can be applied to all provided fields
// *
// * @param array $idsDataFields
// * @param array $schemaErrors
// */
// protected function validateAndFilterFieldsForDirective(array &$idsDataFields, array &$schemaErrors, array &$schemaWarnings)
// {
// $directiveSupportedFieldNames = $this->getFieldNamesToApplyTo();
// // If this function returns an empty array, then it supports all fields, then do nothing
// if (!$directiveSupportedFieldNames) {
// return;
// }
// // Check if all fields are supported by this directive
// $fieldQueryInterpreter = FieldQueryInterpreterFacade::getInstance();
// $failedFields = [];
// foreach ($idsDataFields as $id => &$data_fields) {
// // Get the fieldName for each field
// $nameFields = [];
// foreach ($data_fields['direct'] as $field) {
// $nameFields[$fieldQueryInterpreter->getFieldName($field)] = $field;
// }
// // If any fieldName failed, remove it from the list of fields to execute for this directive
// if ($unsupportedFieldNames = array_diff(array_keys($nameFields), $directiveSupportedFieldNames)) {
// $unsupportedFields = array_map(
// function($fieldName) use ($nameFields) {
// return $nameFields[$fieldName];
// },
// $unsupportedFieldNames
// );
// $failedFields = array_values(array_unique(array_merge(
// $failedFields,
// $unsupportedFields
// )));
// }
// }
// // Give an error message for all failed fields
// if ($failedFields) {
// $translationAPI = TranslationAPIFacade::getInstance();
// $directiveName = $this->getDirectiveName();
// $failedFieldNames = array_map(
// [$fieldQueryInterpreter, 'getFieldName'],
// $failedFields
// );
// if (count($failedFields) == 1) {
// $message = $translationAPI->__('Directive \'%s\' doesn\'t support field \'%s\' (the only supported field names are: \'%s\')', 'component-model');
// } else {
// $message = $translationAPI->__('Directive \'%s\' doesn\'t support fields \'%s\' (the only supported field names are: \'%s\')', 'component-model');
// }
// $failureMessage = sprintf(
// $message,
// $directiveName,
// implode($translationAPI->__('\', \''), $failedFieldNames),
// implode($translationAPI->__('\', \''), $directiveSupportedFieldNames)
// );
// $this->processFailure($failureMessage, $failedFields, $idsDataFields, $schemaErrors, $schemaWarnings);
// }
// }
/**
* Depending on environment configuration, either show a warning,
* or show an error and remove the fields from the directive pipeline for further execution
*/
protected function processFailure(string $failureMessage, array $failedFields, array &$idsDataFields, array &$succeedingPipelineIDsDataFields, array &$schemaErrors, array &$schemaWarnings): void
{
$allFieldsFailed = empty($failedFields);
if ($allFieldsFailed) {
// Remove all fields
$idsDataFieldsToRemove = $idsDataFields;
// Calculate which fields are being removed, to add to the error
foreach ($idsDataFields as $id => &$data_fields) {
$failedFields = array_merge(
$failedFields,
$data_fields['direct']
);
}
$failedFields = array_values(array_unique($failedFields));
} else {
$idsDataFieldsToRemove = [];
// Calculate which fields to remove
foreach ($idsDataFields as $id => &$data_fields) {
$idsDataFieldsToRemove[(string)$id]['direct'] = array_intersect(
$data_fields['direct'],
$failedFields
);
}
}
// If the failure must be processed as an error, we must also remove the fields from the directive pipeline
$removeFieldIfDirectiveFailed = Environment::removeFieldIfDirectiveFailed();
if ($removeFieldIfDirectiveFailed) {
$this->removeIDsDataFields($idsDataFieldsToRemove, $succeedingPipelineIDsDataFields);
}
// Show the failureMessage either as error or as warning
// $fieldQueryInterpreter = FieldQueryInterpreterFacade::getInstance();
$translationAPI = TranslationAPIFacade::getInstance();
$directiveName = $this->getDirectiveName();
// $failedFieldNames = array_map(
// [$fieldQueryInterpreter, 'getFieldName'],
// $failedFields
// );
if ($removeFieldIfDirectiveFailed) {
if (count($failedFields) == 1) {
$message = $translationAPI->__('%s. Field \'%s\' has been removed from the directive pipeline', 'component-model');
} else {
$message = $translationAPI->__('%s. Fields \'%s\' have been removed from the directive pipeline', 'component-model');
}
$schemaErrors[] = [
Tokens::PATH => [implode($translationAPI->__('\', \''), $failedFields), $this->directive],
Tokens::MESSAGE => sprintf(
$message,
$failureMessage,
implode($translationAPI->__('\', \''), $failedFields)
),
];
} else {
if (count($failedFields) == 1) {
$message = $translationAPI->__('%s. Execution of directive \'%s\' has been ignored on field \'%s\'', 'component-model');
} else {
$message = $translationAPI->__('%s. Execution of directive \'%s\' has been ignored on fields \'%s\'', 'component-model');
}
$schemaWarnings[] = [
Tokens::PATH => [implode($translationAPI->__('\', \''), $failedFields), $this->directive],
Tokens::MESSAGE => sprintf(
$message,
$failureMessage,
$directiveName,
implode($translationAPI->__('\', \''), $failedFields)
),
];
}
}
public function getSchemaDefinitionResolver(TypeResolverInterface $typeResolver): ?SchemaDirectiveResolverInterface
{
return null;
}
/**
* Directives may not be directly visible in the schema,
* eg: because their name is duplicated across directives (eg: "cacheControl")
* or because they are used through code (eg: "validateIsUserLoggedIn")
*/
public function skipAddingToSchemaDefinition(): bool
{
return false;
}
public function getSchemaDefinitionForDirective(TypeResolverInterface $typeResolver): array
{
$directiveName = $this->getDirectiveName();
$schemaDefinition = [
SchemaDefinition::ARGNAME_NAME => $directiveName,
SchemaDefinition::ARGNAME_DIRECTIVE_TYPE => $this->getDirectiveType(),
SchemaDefinition::ARGNAME_DIRECTIVE_PIPELINE_POSITION => $this->getPipelinePosition(),
SchemaDefinition::ARGNAME_DIRECTIVE_IS_REPEATABLE => $this->isRepeatable(),
SchemaDefinition::ARGNAME_DIRECTIVE_NEEDS_DATA_TO_EXECUTE => $this->needsIDsDataFieldsToExecute(),
];
if ($limitedToFields = $this->getFieldNamesToApplyTo()) {
$schemaDefinition[SchemaDefinition::ARGNAME_DIRECTIVE_LIMITED_TO_FIELDS] = $limitedToFields;
}
if ($schemaDefinitionResolver = $this->getSchemaDefinitionResolver($typeResolver)) {
if ($description = $schemaDefinitionResolver->getSchemaDirectiveDescription($typeResolver)) {
$schemaDefinition[SchemaDefinition::ARGNAME_DESCRIPTION] = $description;
}
if ($expressions = $schemaDefinitionResolver->getSchemaDirectiveExpressions($typeResolver)) {
$schemaDefinition[SchemaDefinition::ARGNAME_DIRECTIVE_EXPRESSIONS] = $expressions;
}
if ($deprecationDescription = $schemaDefinitionResolver->getSchemaDirectiveDeprecationDescription($typeResolver)) {
$schemaDefinition[SchemaDefinition::ARGNAME_DEPRECATED] = true;
$schemaDefinition[SchemaDefinition::ARGNAME_DEPRECATIONDESCRIPTION] = $deprecationDescription;
}
if ($args = $schemaDefinitionResolver->getFilteredSchemaDirectiveArgs($typeResolver)) {
// Add the args under their name
$nameArgs = [];
foreach ($args as $arg) {
$nameArgs[$arg[SchemaDefinition::ARGNAME_NAME]] = $arg;
}
$schemaDefinition[SchemaDefinition::ARGNAME_ARGS] = $nameArgs;
}
}
/**
* Please notice: the version always comes from the directiveResolver, and not from the schemaDefinitionResolver
* That is because it is the implementer the one who knows what version it is, and not the one defining the interface
* If the interface changes, the implementer will need to change, so the version will be upgraded
* But it could also be that the contract doesn't change, but the implementation changes
* it's really not their responsibility
*/
if (Environment::enableSemanticVersionConstraints()) {
if ($version = $this->getSchemaDirectiveVersion($typeResolver)) {
$schemaDefinition[SchemaDefinition::ARGNAME_VERSION] = $version;
}
}
$this->addSchemaDefinitionForDirective($schemaDefinition);
return $schemaDefinition;
}
/**
* Function to override
*/
protected function addSchemaDefinitionForDirective(array &$schemaDefinition)
{
}
}