Passed
Pull Request — master (#217)
by Christoffer
02:37
created

Executor::createResolveInfo()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 19
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 11
nc 1
nop 6
dl 0
loc 19
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace Digia\GraphQL\Execution;
4
5
use Digia\GraphQL\Error\ExecutionException;
6
use Digia\GraphQL\Error\GraphQLException;
7
use Digia\GraphQL\Error\InvalidTypeException;
8
use Digia\GraphQL\Error\InvariantException;
9
use Digia\GraphQL\Error\UndefinedException;
10
use Digia\GraphQL\Language\Node\FieldNode;
11
use Digia\GraphQL\Language\Node\OperationDefinitionNode;
12
use Digia\GraphQL\Schema\Schema;
13
use Digia\GraphQL\Type\Definition\AbstractTypeInterface;
14
use Digia\GraphQL\Type\Definition\Field;
15
use Digia\GraphQL\Type\Definition\InterfaceType;
16
use Digia\GraphQL\Type\Definition\LeafTypeInterface;
17
use Digia\GraphQL\Type\Definition\ListType;
18
use Digia\GraphQL\Type\Definition\NamedTypeInterface;
19
use Digia\GraphQL\Type\Definition\NonNullType;
20
use Digia\GraphQL\Type\Definition\ObjectType;
21
use Digia\GraphQL\Type\Definition\ScalarType;
22
use Digia\GraphQL\Type\Definition\TypeInterface;
23
use Digia\GraphQL\Type\Definition\UnionType;
24
use InvalidArgumentException;
25
use React\Promise\ExtendedPromiseInterface;
26
use React\Promise\FulfilledPromise;
27
use React\Promise\PromiseInterface;
28
use Throwable;
29
use function Digia\GraphQL\Type\SchemaMetaFieldDefinition;
30
use function Digia\GraphQL\Type\TypeMetaFieldDefinition;
31
use function Digia\GraphQL\Type\TypeNameMetaFieldDefinition;
32
use function Digia\GraphQL\Util\toString;
33
34
class Executor
35
{
36
    /**
37
     * @var ExecutionContext
38
     */
39
    protected $context;
40
41
    /**
42
     * @var OperationDefinitionNode
43
     */
44
    protected $operation;
45
46
    /**
47
     * @var mixed
48
     */
49
    protected $rootValue;
50
51
    /**
52
     * @var FieldCollector
53
     */
54
    protected $fieldCollector;
55
56
    /**
57
     * @var array
58
     */
59
    protected $finalResult;
60
61
    /**
62
     * @var array
63
     */
64
    private static $defaultFieldResolver = [__CLASS__, 'defaultFieldResolver'];
65
66
    /**
67
     * Executor constructor.
68
     * @param ExecutionContext $context
69
     * @param FieldCollector   $fieldCollector
70
     */
71
    public function __construct(ExecutionContext $context, FieldCollector $fieldCollector)
72
    {
73
        $this->context        = $context;
74
        $this->fieldCollector = $fieldCollector;
75
    }
76
77
    /**
78
     * @return array|null
79
     * @throws ExecutionException
80
     * @throws \Throwable
81
     */
82
    public function execute(): ?array
83
    {
84
        $operation = $this->context->getOperation();
85
        $schema    = $this->context->getSchema();
86
87
        $path = [];
88
89
        $objectType = $this->getOperationType($schema, $operation);
90
91
        $fields               = [];
92
        $visitedFragmentNames = [];
93
94
        try {
95
            $fields = $this->fieldCollector->collectFields(
96
                $objectType,
97
                $this->context->getOperation()->getSelectionSet(),
98
                $fields,
99
                $visitedFragmentNames
100
            );
101
102
            $rootValue = $this->context->getRootValue();
103
104
            $result = $operation->getOperation() === 'mutation'
105
                ? $this->executeFieldsSerially($objectType, $rootValue, $path, $fields)
106
                : $this->executeFields($objectType, $rootValue, $path, $fields);
107
        } catch (\Exception $ex) {
108
            $this->context->addError(new ExecutionException($ex->getMessage()));
109
110
            return [null];
111
        }
112
113
        return $result;
114
    }
115
116
    /**
117
     * @param Schema                  $schema
118
     * @param OperationDefinitionNode $operation
119
     * @return NamedTypeInterface|ObjectType
120
     * @throws ExecutionException
121
     */
122
    public function getOperationType(Schema $schema, OperationDefinitionNode $operation): NamedTypeInterface
123
    {
124
        switch ($operation->getOperation()) {
125
            case 'query':
126
                return $schema->getQueryType();
0 ignored issues
show
Bug Best Practice introduced by
The expression return $schema->getQueryType() could return the type null which is incompatible with the type-hinted return Digia\GraphQL\Type\Definition\NamedTypeInterface. Consider adding an additional type-check to rule them out.
Loading history...
127
            case 'mutation':
128
                $mutationType = $schema->getMutationType();
129
                if (null === $mutationType) {
130
                    throw new ExecutionException(
131
                        'Schema is not configured for mutations',
132
                        [$operation]
133
                    );
134
                }
135
                return $mutationType;
136
            case 'subscription':
137
                $subscriptionType = $schema->getSubscriptionType();
138
                if (null === $subscriptionType) {
139
                    throw new ExecutionException(
140
                        'Schema is not configured for subscriptions',
141
                        [$operation]
142
                    );
143
                }
144
                return $subscriptionType;
145
            default:
146
                throw new ExecutionException(
147
                    'Can only execute queries, mutations and subscriptions',
148
                    [$operation]
149
                );
150
        }
151
    }
152
153
    /**
154
     * Implements the "Evaluating selection sets" section of the spec for "write" mode.
155
     *
156
     * @param ObjectType $objectType
157
     * @param mixed      $rootValue
158
     * @param array      $path
159
     * @param array      $fields
160
     * @return array
161
     * @throws InvalidArgumentException
162
     * @throws Throwable
163
     */
164
    public function executeFieldsSerially(
165
        ObjectType $objectType,
166
        $rootValue,
167
        array $path,
168
        array $fields
169
    ): array {
170
        $finalResults = [];
171
172
        $promise = new FulfilledPromise([]);
173
174
        $resolve = function ($results, $fieldName, $path, $objectType, $rootValue, $fieldNodes) {
175
            $fieldPath   = $path;
176
            $fieldPath[] = $fieldName;
177
            try {
178
                $result = $this->resolveField($objectType, $rootValue, $fieldNodes, $fieldPath);
179
            } catch (UndefinedException $ex) {
180
                return null;
181
            }
182
183
            if ($this->isPromise($result)) {
184
                /** @var ExtendedPromiseInterface $result */
185
                return $result->then(function ($resolvedResult) use ($fieldName, $results) {
186
                    $results[$fieldName] = $resolvedResult;
187
                    return $results;
188
                });
189
            }
190
191
            $results[$fieldName] = $result;
192
193
            return $results;
194
        };
195
196
        foreach ($fields as $fieldName => $fieldNodes) {
197
            $promise = $promise->then(function ($resolvedResults) use (
198
                $resolve,
199
                $fieldName,
200
                $path,
201
                $objectType,
202
                $rootValue,
203
                $fieldNodes
204
            ) {
205
                return $resolve($resolvedResults, $fieldName, $path, $objectType, $rootValue, $fieldNodes);
206
            });
207
        }
208
209
        $promise->then(function ($resolvedResults) use (&$finalResults) {
210
            $finalResults = $resolvedResults ?? [];
211
        });
212
213
        return $finalResults;
214
    }
215
216
    /**
217
     * @param Schema     $schema
218
     * @param ObjectType $parentType
219
     * @param string     $fieldName
220
     * @return Field|null
221
     */
222
    public function getFieldDefinition(
223
        Schema $schema,
224
        ObjectType $parentType,
225
        string $fieldName
226
    ): ?Field {
227
        $schemaMetaFieldDefinition   = SchemaMetaFieldDefinition();
228
        $typeMetaFieldDefinition     = TypeMetaFieldDefinition();
229
        $typeNameMetaFieldDefinition = TypeNameMetaFieldDefinition();
230
231
        if ($fieldName === $schemaMetaFieldDefinition->getName() && $schema->getQueryType() === $parentType) {
232
            return $schemaMetaFieldDefinition;
233
        }
234
235
        if ($fieldName === $typeMetaFieldDefinition->getName() && $schema->getQueryType() === $parentType) {
236
            return $typeMetaFieldDefinition;
237
        }
238
239
        if ($fieldName === $typeNameMetaFieldDefinition->getName()) {
240
            return $typeNameMetaFieldDefinition;
241
        }
242
243
        $fields = $parentType->getFields();
244
245
        return $fields[$fieldName] ?? null;
246
    }
247
248
    /**
249
     * @param TypeInterface $fieldType
250
     * @param FieldNode[]   $fieldNodes
251
     * @param ResolveInfo   $info
252
     * @param array         $path
253
     * @param mixed         $result
254
     * @return array|mixed|null
255
     * @throws \Throwable
256
     */
257
    public function completeValueCatchingError(
258
        TypeInterface $fieldType,
259
        array $fieldNodes,
260
        ResolveInfo $info,
261
        array $path,
262
        &$result
263
    ) {
264
        if ($fieldType instanceof NonNullType) {
265
            return $this->completeValueWithLocatedError(
266
                $fieldType,
267
                $fieldNodes,
268
                $info,
269
                $path,
270
                $result
271
            );
272
        }
273
274
        try {
275
            $completed = $this->completeValueWithLocatedError(
276
                $fieldType,
277
                $fieldNodes,
278
                $info,
279
                $path,
280
                $result
281
            );
282
283
            if ($this->isPromise($completed)) {
284
                $context = $this->context;
285
                /** @var ExtendedPromiseInterface $completed */
286
                return $completed->then(null, function ($error) use ($context, $fieldNodes, $path) {
287
                    //@TODO Handle $error better
288
                    if ($error instanceof \Exception) {
289
                        $context->addError($this->buildLocatedError($error, $fieldNodes, $path));
290
                    } else {
291
                        $context->addError(
292
                            $this->buildLocatedError(
293
                                new ExecutionException($error ?? 'An unknown error occurred.'),
294
                                $fieldNodes,
295
                                $path
296
                            )
297
                        );
298
                    }
299
                    return new FulfilledPromise(null);
300
                });
301
            }
302
303
            return $completed;
304
        } catch (\Exception $ex) {
305
            $this->context->addError($this->buildLocatedError($ex, $fieldNodes, $path));
306
            return null;
307
        }
308
    }
309
310
311
    /**
312
     * @param TypeInterface $fieldType
313
     * @param FieldNode[]   $fieldNodes
314
     * @param ResolveInfo   $info
315
     * @param array         $path
316
     * @param mixed         $result
317
     * @return array|mixed
318
     * @throws \Throwable
319
     */
320
    public function completeValueWithLocatedError(
321
        TypeInterface $fieldType,
322
        array $fieldNodes,
323
        ResolveInfo $info,
324
        array $path,
325
        $result
326
    ) {
327
        try {
328
            $completed = $this->completeValue(
329
                $fieldType,
330
                $fieldNodes,
331
                $info,
332
                $path,
333
                $result
334
            );
335
336
            return $completed;
337
        } catch (\Throwable $ex) {
338
            throw $this->buildLocatedError($ex, $fieldNodes, $path);
339
        }
340
    }
341
342
    /**
343
     * Implements the "Evaluating selection sets" section of the spec for "read" mode.
344
     *
345
     * @param ObjectType $objectType
346
     * @param mixed      $rootValue
347
     * @param array      $path
348
     * @param array      $fields
349
     * @return array
350
     * @throws \Throwable
351
     */
352
    protected function executeFields(
353
        ObjectType $objectType,
354
        $rootValue,
355
        array $path,
356
        array $fields
357
    ): array {
358
        $finalResults       = [];
359
        $doesContainPromise = false;
360
361
        foreach ($fields as $fieldName => $fieldNodes) {
362
            $fieldPath   = $path;
363
            $fieldPath[] = $fieldName;
364
365
            try {
366
                $result = $this->resolveField($objectType, $rootValue, $fieldNodes, $fieldPath);
367
            } catch (UndefinedException $ex) {
368
                continue;
369
            }
370
371
            $doesContainPromise = $doesContainPromise || $this->isPromise($result);
372
373
            $finalResults[$fieldName] = $result;
374
        }
375
376
        if ($doesContainPromise) {
377
            $keys    = array_keys($finalResults);
378
            $promise = \React\Promise\all(array_values($finalResults));
379
            $promise->then(function ($values) use ($keys, &$finalResults) {
380
                /** @noinspection ForeachSourceInspection */
381
                foreach ($values as $i => $value) {
382
                    $finalResults[$keys[$i]] = $value;
383
                }
384
            });
385
        }
386
387
        return $finalResults;
388
    }
389
390
    /**
391
     * @param ObjectType  $parentType
392
     * @param mixed       $rootValue
393
     * @param FieldNode[] $fieldNodes
394
     * @param array       $path
395
     * @return array|mixed|null
396
     * @throws UndefinedException
397
     * @throws Throwable
398
     */
399
    protected function resolveField(
400
        ObjectType $parentType,
401
        $rootValue,
402
        array $fieldNodes,
403
        array $path
404
    ) {
405
        /** @var FieldNode $fieldNode */
406
        $fieldNode = $fieldNodes[0];
407
408
        $field = $this->getFieldDefinition($this->context->getSchema(), $parentType, $fieldNode->getNameValue());
409
410
        if (null === $field) {
411
            throw new UndefinedException('Undefined field definition.');
412
        }
413
414
        $info = $this->createResolveInfo($fieldNodes, $fieldNode, $field, $parentType, $path, $this->context);
415
416
        $resolveCallback = $this->determineResolveCallback($field, $parentType);
417
418
        $result = $this->resolveFieldValueOrError(
419
            $field,
420
            $fieldNode,
421
            $resolveCallback,
422
            $rootValue,
423
            $this->context,
424
            $info
425
        );
426
427
        $result = $this->completeValueCatchingError(
428
            $field->getType(),
429
            $fieldNodes,
430
            $info,
431
            $path,
432
            $result
433
        );
434
435
        return $result;
436
    }
437
438
    /**
439
     * @param Field      $field
440
     * @param ObjectType $objectType
441
     * @return callable|mixed|null
442
     */
443
    protected function determineResolveCallback(Field $field, ObjectType $objectType)
444
    {
445
        if ($field->hasResolveCallback()) {
446
            return $field->getResolveCallback();
447
        }
448
449
        if ($objectType->hasResolveCallback()) {
450
            return $objectType->getResolveCallback();
451
        }
452
453
        return $this->context->getFieldResolver() ?? self::$defaultFieldResolver;
454
    }
455
456
    /**
457
     * @param TypeInterface $returnType
458
     * @param FieldNode[]   $fieldNodes
459
     * @param ResolveInfo   $info
460
     * @param array         $path
461
     * @param mixed         $result
462
     * @return array|mixed
463
     * @throws InvariantException
464
     * @throws InvalidTypeException
465
     * @throws ExecutionException
466
     * @throws \Throwable
467
     */
468
    protected function completeValue(
469
        TypeInterface $returnType,
470
        array $fieldNodes,
471
        ResolveInfo $info,
472
        array $path,
473
        &$result
474
    ) {
475
        if ($this->isPromise($result)) {
476
            /** @var ExtendedPromiseInterface $result */
477
            return $result->then(function (&$value) use ($returnType, $fieldNodes, $info, $path) {
478
                return $this->completeValue($returnType, $fieldNodes, $info, $path, $value);
479
            });
480
        }
481
482
        if ($result instanceof \Throwable) {
483
            throw $result;
484
        }
485
486
        // If result is null-like, return null.
487
        if (null === $result) {
488
            return null;
489
        }
490
491
        if ($returnType instanceof NonNullType) {
492
            $completed = $this->completeValue(
493
                $returnType->getOfType(),
494
                $fieldNodes,
495
                $info,
496
                $path,
497
                $result
498
            );
499
500
            if ($completed === null) {
501
                throw new ExecutionException(
502
                    \sprintf(
503
                        'Cannot return null for non-nullable field %s.%s.',
504
                        $info->getParentType(),
505
                        $info->getFieldName()
506
                    )
507
                );
508
            }
509
510
            return $completed;
511
        }
512
513
        // If field type is List, complete each item in the list with the inner type
514
        if ($returnType instanceof ListType) {
515
            return $this->completeListValue($returnType, $fieldNodes, $info, $path, $result);
516
        }
517
518
        // If field type is Scalar or Enum, serialize to a valid value, returning
519
        // null if serialization is not possible.
520
        if ($returnType instanceof LeafTypeInterface) {
521
            return $this->completeLeafValue($returnType, $result);
522
        }
523
524
        // TODO: Make a function for checking abstract type?
525
        if ($returnType instanceof InterfaceType || $returnType instanceof UnionType) {
526
            return $this->completeAbstractValue($returnType, $fieldNodes, $info, $path, $result);
527
        }
528
529
        // Field type must be Object, Interface or Union and expect sub-selections.
530
        if ($returnType instanceof ObjectType) {
531
            return $this->completeObjectValue($returnType, $fieldNodes, $info, $path, $result);
532
        }
533
534
        throw new ExecutionException("Cannot complete value of unexpected type \"{$returnType}\".");
535
    }
536
537
    /**
538
     * @param AbstractTypeInterface $returnType
539
     * @param FieldNode[]           $fieldNodes
540
     * @param ResolveInfo           $info
541
     * @param array                 $path
542
     * @param mixed                 $result
543
     * @return array|PromiseInterface
544
     * @throws ExecutionException
545
     * @throws InvalidTypeException
546
     * @throws InvariantException
547
     * @throws \Throwable
548
     */
549
    protected function completeAbstractValue(
550
        AbstractTypeInterface $returnType,
551
        array $fieldNodes,
552
        ResolveInfo $info,
553
        array $path,
554
        &$result
555
    ) {
556
        $runtimeType = $returnType->resolveType($result, $this->context->getContextValue(), $info);
557
558
        if (null === $runtimeType) {
559
            // TODO: Display warning
560
            $runtimeType = $this->defaultTypeResolver($result, $this->context->getContextValue(), $info, $returnType);
561
        }
562
563
        if ($this->isPromise($runtimeType)) {
564
            /** @var ExtendedPromiseInterface $runtimeType */
565
            return $runtimeType->then(function ($resolvedRuntimeType) use (
566
                $returnType,
567
                $fieldNodes,
568
                $info,
569
                $path,
570
                &$result
571
            ) {
572
                return $this->completeObjectValue(
573
                    $this->ensureValidRuntimeType($resolvedRuntimeType, $returnType, $info, $result),
574
                    $fieldNodes,
575
                    $info,
576
                    $path,
577
                    $result
578
                );
579
            });
580
        }
581
582
        return $this->completeObjectValue(
583
            $this->ensureValidRuntimeType($runtimeType, $returnType, $info, $result),
584
            $fieldNodes,
585
            $info,
586
            $path,
587
            $result
588
        );
589
    }
590
591
    /**
592
     * @param NamedTypeInterface|string $runtimeTypeOrName
593
     * @param AbstractTypeInterface     $returnType
594
     * @param ResolveInfo               $info
595
     * @param mixed                     $result
596
     * @return TypeInterface|ObjectType|null
597
     * @throws ExecutionException
598
     * @throws InvariantException
599
     */
600
    protected function ensureValidRuntimeType(
601
        $runtimeTypeOrName,
602
        AbstractTypeInterface $returnType,
603
        ResolveInfo $info,
604
        &$result
605
    ) {
606
        /** @var NamedTypeInterface $runtimeType */
607
        $runtimeType = \is_string($runtimeTypeOrName)
608
            ? $this->context->getSchema()->getType($runtimeTypeOrName)
609
            : $runtimeTypeOrName;
610
611
        $runtimeTypeName = $runtimeType->getName();
612
        $returnTypeName  = $returnType->getName();
613
614
        if (!$runtimeType instanceof ObjectType) {
615
            $parentTypeName = $info->getParentType()->getName();
616
            $fieldName      = $info->getFieldName();
617
618
            throw new ExecutionException(
619
                \sprintf(
620
                    'Abstract type %s must resolve to an Object type at runtime for field %s.%s ' .
621
                    'with value "%s", received "%s".',
622
                    $returnTypeName,
623
                    $parentTypeName,
624
                    $fieldName,
625
                    $result,
626
                    $runtimeTypeName
627
                )
628
            );
629
        }
630
631
        if (!$this->context->getSchema()->isPossibleType($returnType, $runtimeType)) {
632
            throw new ExecutionException(
633
                \sprintf('Runtime Object type "%s" is not a possible type for "%s".', $runtimeTypeName, $returnTypeName)
634
            );
635
        }
636
637
        if ($runtimeType !== $this->context->getSchema()->getType($runtimeType->getName())) {
0 ignored issues
show
introduced by
The condition $runtimeType !== $this->...runtimeType->getName()) is always true.
Loading history...
638
            throw new ExecutionException(
639
                \sprintf(
640
                    'Schema must contain unique named types but contains multiple types named "%s". ' .
641
                    'Make sure that `resolveType` function of abstract type "%s" returns the same ' .
642
                    'type instance as referenced anywhere else within the schema.',
643
                    $runtimeTypeName,
644
                    $returnTypeName
645
                )
646
            );
647
        }
648
649
        return $runtimeType;
650
    }
651
652
    /**
653
     * @param mixed                 $value
654
     * @param mixed                 $context
655
     * @param ResolveInfo           $info
656
     * @param AbstractTypeInterface $abstractType
657
     * @return NamedTypeInterface|mixed|null
658
     * @throws InvariantException
659
     */
660
    protected function defaultTypeResolver(
661
        $value,
662
        $context,
663
        ResolveInfo $info,
664
        AbstractTypeInterface $abstractType
665
    ) {
666
        /** @var ObjectType[] $possibleTypes */
667
        $possibleTypes           = $info->getSchema()->getPossibleTypes($abstractType);
668
        $promisedIsTypeOfResults = [];
669
670
        foreach ($possibleTypes as $index => $type) {
671
            $isTypeOfResult = $type->isTypeOf($value, $context, $info);
672
            if (null !== $isTypeOfResult) {
673
                if ($this->isPromise($isTypeOfResult)) {
674
                    $promisedIsTypeOfResults[$index] = $isTypeOfResult;
675
                    continue;
676
                }
677
678
                if ($isTypeOfResult === true) {
679
                    return $type;
680
                }
681
682
                if (\is_array($value)) {
683
                    // TODO: Make `type` configurable
684
                    /** @noinspection NestedPositiveIfStatementsInspection */
685
                    if (isset($value['type']) && $value['type'] === $type->getName()) {
686
                        return $type;
687
                    }
688
                }
689
            }
690
        }
691
692
        if (!empty($promisedIsTypeOfResults)) {
693
            return \React\Promise\all($promisedIsTypeOfResults)
694
                ->then(function ($isTypeOfResults) use ($possibleTypes) {
695
                    /** @noinspection ForeachSourceInspection */
696
                    foreach ($isTypeOfResults as $index => $result) {
697
                        if ($result) {
698
                            return $possibleTypes[$index];
699
                        }
700
                    }
701
                    return null;
702
                });
703
        }
704
705
        return null;
706
    }
707
708
    /**
709
     * @param ListType    $returnType
710
     * @param FieldNode[] $fieldNodes
711
     * @param ResolveInfo $info
712
     * @param array       $path
713
     * @param mixed       $result
714
     * @return array|\React\Promise\Promise
715
     * @throws \Throwable
716
     */
717
    protected function completeListValue(
718
        ListType $returnType,
719
        array $fieldNodes,
720
        ResolveInfo $info,
721
        array $path,
722
        &$result
723
    ) {
724
        $itemType = $returnType->getOfType();
725
726
        $completedItems     = [];
727
        $doesContainPromise = false;
728
729
        if (!\is_array($result) && !($result instanceof \Traversable)) {
730
            /** @noinspection ThrowRawExceptionInspection */
731
            throw new \Exception(
732
                \sprintf(
733
                    'Expected Array or Traversable, but did not find one for field %s.%s.',
734
                    $info->getParentType()->getName(),
735
                    $info->getFieldName()
736
                )
737
            );
738
        }
739
740
        foreach ($result as $key => $item) {
741
            $fieldPath          = $path;
742
            $fieldPath[]        = $key;
743
            $completedItem      = $this->completeValueCatchingError($itemType, $fieldNodes, $info, $fieldPath, $item);
744
            $completedItems[]   = $completedItem;
745
            $doesContainPromise = $doesContainPromise || $this->isPromise($completedItem);
746
        }
747
748
        return $doesContainPromise
749
            ? \React\Promise\all($completedItems)
750
            : $completedItems;
751
    }
752
753
    /**
754
     * @param LeafTypeInterface $returnType
755
     * @param mixed             $result
756
     * @return mixed
757
     * @throws ExecutionException
758
     */
759
    protected function completeLeafValue(LeafTypeInterface $returnType, &$result)
760
    {
761
        /** @var ScalarType $returnType */
762
        $serializedResult = $returnType->serialize($result);
763
764
        if ($serializedResult === null) {
765
            // TODO: Make a function for this type of exception
766
            throw new ExecutionException(
767
                \sprintf('Expected value of type "%s" but received: %s.', (string)$returnType, toString($result))
768
            );
769
        }
770
771
        return $serializedResult;
772
    }
773
774
    /**
775
     * @param ObjectType  $returnType
776
     * @param array       $fieldNodes
777
     * @param ResolveInfo $info
778
     * @param array       $path
779
     * @param mixed       $result
780
     * @return array
781
     * @throws ExecutionException
782
     * @throws InvalidTypeException
783
     * @throws InvariantException
784
     * @throws \Throwable
785
     */
786
    protected function completeObjectValue(
787
        ObjectType $returnType,
788
        array $fieldNodes,
789
        ResolveInfo $info,
790
        array $path,
791
        &$result
792
    ): array {
793
        if (null !== $returnType->getIsTypeOf()) {
794
            $isTypeOf = $returnType->isTypeOf($result, $this->context->getContextValue(), $info);
795
796
            // TODO: Check for promise?
797
            if (!$isTypeOf) {
798
                throw new ExecutionException(
799
                    sprintf('Expected value of type "%s" but received: %s.', (string)$returnType, toString($result))
800
                );
801
            }
802
        }
803
804
        return $this->executeSubFields($returnType, $fieldNodes, $path, $result);
805
    }
806
807
    /**
808
     * @param Field            $field
809
     * @param FieldNode        $fieldNode
810
     * @param callable         $resolveCallback
811
     * @param mixed            $rootValue
812
     * @param ExecutionContext $context
813
     * @param ResolveInfo      $info
814
     * @return array|\Throwable
815
     */
816
    protected function resolveFieldValueOrError(
817
        Field $field,
818
        FieldNode $fieldNode,
819
        ?callable $resolveCallback,
820
        $rootValue,
821
        ExecutionContext $context,
822
        ResolveInfo $info
823
    ) {
824
        try {
825
            $result = $resolveCallback(
826
                $rootValue,
827
                coerceArgumentValues($field, $fieldNode, $context->getVariableValues()),
828
                $context->getContextValue(),
829
                $info
830
            );
831
        } catch (\Throwable $error) {
832
            return $error;
833
        }
834
835
        return $result;
836
    }
837
838
    /**
839
     * @param ObjectType  $returnType
840
     * @param FieldNode[] $fieldNodes
841
     * @param array       $path
842
     * @param mixed       $result
843
     * @return array
844
     * @throws ExecutionException
845
     * @throws InvalidTypeException
846
     * @throws InvariantException
847
     * @throws Throwable
848
     */
849
    protected function executeSubFields(
850
        ObjectType $returnType,
851
        array $fieldNodes,
852
        array $path,
853
        &$result
854
    ): array {
855
        $subFields            = [];
856
        $visitedFragmentNames = [];
857
858
        foreach ($fieldNodes as $fieldNode) {
859
            if (null !== $fieldNode->getSelectionSet()) {
860
                $subFields = $this->fieldCollector->collectFields(
861
                    $returnType,
862
                    $fieldNode->getSelectionSet(),
863
                    $subFields,
864
                    $visitedFragmentNames
865
                );
866
            }
867
        }
868
869
        if (!empty($subFields)) {
870
            return $this->executeFields($returnType, $result, $path, $subFields);
871
        }
872
873
        return $result;
874
    }
875
876
    /**
877
     * @param $value
878
     * @return bool
879
     */
880
    protected function isPromise($value): bool
881
    {
882
        return $value instanceof ExtendedPromiseInterface;
883
    }
884
885
    /**
886
     * @param \Throwable $originalException
887
     * @param array      $nodes
888
     * @param array      $path
889
     * @return ExecutionException
890
     */
891
    protected function buildLocatedError(
892
        \Throwable $originalException,
893
        array $nodes = [],
894
        array $path = []
895
    ): ExecutionException {
896
        return new ExecutionException(
897
            $originalException->getMessage(),
898
            $originalException instanceof GraphQLException
899
                ? $originalException->getNodes()
900
                : $nodes,
901
            $originalException instanceof GraphQLException
902
                ? $originalException->getSource()
903
                : null,
904
            $originalException instanceof GraphQLException
905
                ? $originalException->getPositions()
906
                : null,
907
            $originalException instanceof GraphQLException
908
                ? ($originalException->getPath() ?? $path)
909
                : $path,
910
            $originalException
911
        );
912
    }
913
914
    /**
915
     * @param FieldNode[]      $fieldNodes
916
     * @param FieldNode        $fieldNode
917
     * @param Field            $field
918
     * @param ObjectType       $parentType
919
     * @param array|null       $path
920
     * @param ExecutionContext $context
921
     * @return ResolveInfo
922
     */
923
    protected function createResolveInfo(
924
        array $fieldNodes,
925
        FieldNode $fieldNode,
926
        Field $field,
927
        ObjectType $parentType,
928
        ?array $path,
929
        ExecutionContext $context
930
    ): ResolveInfo {
931
        return new ResolveInfo(
932
            $fieldNode->getNameValue(),
933
            $fieldNodes,
934
            $field->getType(),
935
            $parentType,
936
            $path,
937
            $context->getSchema(),
938
            $context->getFragments(),
939
            $context->getRootValue(),
940
            $context->getOperation(),
941
            $context->getVariableValues()
942
        );
943
    }
944
945
    /**
946
     * Try to resolve a field without any field resolver function.
947
     *
948
     * @param array|object $rootValue
949
     * @param array        $arguments
950
     * @param mixed        $contextValues
951
     * @param ResolveInfo  $info
952
     * @return mixed|null
953
     */
954
    public static function defaultFieldResolver($rootValue, array $arguments, $contextValues, ResolveInfo $info)
955
    {
956
        $fieldName = $info->getFieldName();
957
        $property  = null;
958
959
        if (\is_array($rootValue) && isset($rootValue[$fieldName])) {
960
            $property = $rootValue[$fieldName];
961
        }
962
963
        if (\is_object($rootValue)) {
964
            $getter = 'get' . \ucfirst($fieldName);
965
            if (\method_exists($rootValue, $getter)) {
966
                $property = $rootValue->{$getter}();
967
            } elseif (\method_exists($rootValue, $fieldName)) {
968
                $property = $rootValue->{$fieldName}($rootValue, $arguments, $contextValues, $info);
969
            } elseif (\property_exists($rootValue, $fieldName)) {
970
                $property = $rootValue->{$fieldName};
971
            }
972
        }
973
974
        return \is_callable($property)
975
            ? $property($rootValue, $arguments, $contextValues, $info)
976
            : $property;
977
    }
978
}
979