Passed
Pull Request — master (#297)
by Christoffer
04:04 queued 01:36
created

Executor::isPromise()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
eloc 1
nc 1
nop 1
1
<?php
2
3
namespace Digia\GraphQL\Execution;
4
5
use Digia\GraphQL\Error\ErrorHandlerInterface;
6
use Digia\GraphQL\Error\ExecutionException;
7
use Digia\GraphQL\Error\GraphQLException;
8
use Digia\GraphQL\Error\InvalidTypeException;
9
use Digia\GraphQL\Error\InvariantException;
10
use Digia\GraphQL\Error\UndefinedException;
11
use Digia\GraphQL\Language\Node\FieldNode;
12
use Digia\GraphQL\Language\Node\OperationDefinitionNode;
13
use Digia\GraphQL\Schema\Schema;
14
use Digia\GraphQL\Type\Definition\AbstractTypeInterface;
15
use Digia\GraphQL\Type\Definition\Field;
16
use Digia\GraphQL\Type\Definition\InterfaceType;
17
use Digia\GraphQL\Type\Definition\LeafTypeInterface;
18
use Digia\GraphQL\Type\Definition\ListType;
19
use Digia\GraphQL\Type\Definition\NamedTypeInterface;
20
use Digia\GraphQL\Type\Definition\NonNullType;
21
use Digia\GraphQL\Type\Definition\ObjectType;
22
use Digia\GraphQL\Type\Definition\SerializableTypeInterface;
23
use Digia\GraphQL\Type\Definition\TypeInterface;
24
use Digia\GraphQL\Type\Definition\UnionType;
25
use React\Promise\ExtendedPromiseInterface;
26
use React\Promise\FulfilledPromise;
27
use React\Promise\PromiseInterface;
28
use function Digia\GraphQL\Type\SchemaMetaFieldDefinition;
29
use function Digia\GraphQL\Type\TypeMetaFieldDefinition;
30
use function Digia\GraphQL\Type\TypeNameMetaFieldDefinition;
31
use function Digia\GraphQL\Util\toString;
32
use function React\Promise\all as promiseAll;
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 ErrorHandlerInterface|null
63
     */
64
    protected $errorHandler;
65
66
    /**
67
     * @var array
68
     */
69
    private static $defaultFieldResolver = [__CLASS__, 'defaultFieldResolver'];
70
71
    /**
72
     * Executor constructor.
73
     *
74
     * @param ExecutionContext           $context
75
     * @param FieldCollector             $fieldCollector
76
     * @param ErrorHandlerInterface|null $errorHandler
77
     */
78
    public function __construct(
79
        ExecutionContext $context,
80
        FieldCollector $fieldCollector,
81
        ?ErrorHandlerInterface $errorHandler = null
82
    ) {
83
        $this->context        = $context;
84
        $this->fieldCollector = $fieldCollector;
85
        $this->errorHandler   = $errorHandler;
86
    }
87
88
    /**
89
     * @return array|null
90
     * @throws ExecutionException
91
     * @throws \Throwable
92
     */
93
    public function execute(): ?array
94
    {
95
        $schema    = $this->context->getSchema();
96
        $operation = $this->context->getOperation();
97
        $rootValue = $this->context->getRootValue();
98
99
        $objectType = $this->getOperationType($schema, $operation);
100
101
        $fields               = [];
102
        $visitedFragmentNames = [];
103
        $path                 = [];
104
105
        $fields = $this->fieldCollector->collectFields(
106
            $objectType,
107
            $operation->getSelectionSet(),
108
            $fields,
109
            $visitedFragmentNames
110
        );
111
112
        try {
113
            $result = $operation->getOperation() === 'mutation'
114
                ? $this->executeFieldsSerially($objectType, $rootValue, $path, $fields)
115
                : $this->executeFields($objectType, $rootValue, $path, $fields);
116
        } catch (\Throwable $ex) {
117
            $this->handleError(new ExecutionException($ex->getMessage(), null, null, null, null, null, $ex));
118
            return null;
119
        }
120
121
        return $result;
122
    }
123
124
    /**
125
     * @param Schema                  $schema
126
     * @param OperationDefinitionNode $operation
127
     *
128
     * @return ObjectType|null
129
     * @throws ExecutionException
130
     */
131
    public function getOperationType(Schema $schema, OperationDefinitionNode $operation): ?ObjectType
132
    {
133
        switch ($operation->getOperation()) {
134
            case 'query':
135
                return $schema->getQueryType();
136
            case 'mutation':
137
                $mutationType = $schema->getMutationType();
138
                if (null === $mutationType) {
139
                    throw new ExecutionException(
140
                        'Schema is not configured for mutations',
141
                        [$operation]
142
                    );
143
                }
144
145
                return $mutationType;
146
            case 'subscription':
147
                $subscriptionType = $schema->getSubscriptionType();
148
                if (null === $subscriptionType) {
149
                    throw new ExecutionException(
150
                        'Schema is not configured for subscriptions',
151
                        [$operation]
152
                    );
153
                }
154
155
                return $subscriptionType;
156
            default:
157
                throw new ExecutionException(
158
                    'Can only execute queries, mutations and subscriptions',
159
                    [$operation]
160
                );
161
        }
162
    }
163
164
    /**
165
     * Implements the "Evaluating selection sets" section of the spec for "write" mode.
166
     *
167
     * @param ObjectType $objectType
168
     * @param mixed      $rootValue
169
     * @param array      $path
170
     * @param array      $fields
171
     *
172
     * @return array
173
     */
174
    public function executeFieldsSerially(
175
        ObjectType $objectType,
176
        $rootValue,
177
        array $path,
178
        array $fields
179
    ): array {
180
        $finalResults = [];
181
182
        $promise = new FulfilledPromise([]);
183
184
        $resolve = function ($results, $fieldName, $path, $objectType, $rootValue, $fieldNodes) {
185
            $fieldPath   = $path;
186
            $fieldPath[] = $fieldName;
187
            try {
188
                $result = $this->resolveField($objectType, $rootValue, $fieldNodes, $fieldPath);
189
            } catch (UndefinedException $ex) {
190
                return null;
191
            }
192
193
            if ($result instanceof ExtendedPromiseInterface) {
194
                return $result->then(function ($resolvedResult) use ($fieldName, $results) {
195
                    $results[$fieldName] = $resolvedResult;
196
197
                    return $results;
198
                });
199
            }
200
201
            $results[$fieldName] = $result;
202
203
            return $results;
204
        };
205
206
        foreach ($fields as $fieldName => $fieldNodes) {
207
            $promise = $promise->then(function ($resolvedResults) use (
208
                $resolve,
209
                $fieldName,
210
                $path,
211
                $objectType,
212
                $rootValue,
213
                $fieldNodes
214
            ) {
215
                return $resolve($resolvedResults, $fieldName, $path, $objectType, $rootValue, $fieldNodes);
216
            });
217
        }
218
219
        $promise->then(function ($resolvedResults) use (&$finalResults) {
220
            $finalResults = $resolvedResults ?? [];
221
        })->otherwise(function (ExecutionException $ex) {
222
            $this->handleError($ex);
223
        });
224
225
        return $finalResults;
226
    }
227
228
    /**
229
     * @param Schema     $schema
230
     * @param ObjectType $parentType
231
     * @param string     $fieldName
232
     *
233
     * @return Field|null
234
     */
235
    public function getFieldDefinition(
236
        Schema $schema,
237
        ObjectType $parentType,
238
        string $fieldName
239
    ): ?Field {
240
        $schemaMetaFieldDefinition   = SchemaMetaFieldDefinition();
241
        $typeMetaFieldDefinition     = TypeMetaFieldDefinition();
242
        $typeNameMetaFieldDefinition = TypeNameMetaFieldDefinition();
243
244
        if ($fieldName === $schemaMetaFieldDefinition->getName() && $schema->getQueryType() === $parentType) {
245
            return $schemaMetaFieldDefinition;
246
        }
247
248
        if ($fieldName === $typeMetaFieldDefinition->getName() && $schema->getQueryType() === $parentType) {
249
            return $typeMetaFieldDefinition;
250
        }
251
252
        if ($fieldName === $typeNameMetaFieldDefinition->getName()) {
253
            return $typeNameMetaFieldDefinition;
254
        }
255
256
        /** @noinspection PhpUnhandledExceptionInspection */
257
        $fields = $parentType->getFields();
258
259
        return $fields[$fieldName] ?? null;
260
    }
261
262
    /**
263
     * @param TypeInterface $fieldType
264
     * @param FieldNode[]   $fieldNodes
265
     * @param ResolveInfo   $info
266
     * @param array         $path
267
     * @param mixed         $result
268
     *
269
     * @return array|mixed|null
270
     * @throws \Throwable
271
     */
272
    public function completeValueCatchingError(
273
        TypeInterface $fieldType,
274
        array $fieldNodes,
275
        ResolveInfo $info,
276
        array $path,
277
        &$result
278
    ) {
279
        if ($fieldType instanceof NonNullType) {
280
            return $this->completeValueWithLocatedError(
281
                $fieldType,
282
                $fieldNodes,
283
                $info,
284
                $path,
285
                $result
286
            );
287
        }
288
289
        try {
290
            $completed = $this->completeValueWithLocatedError(
291
                $fieldType,
292
                $fieldNodes,
293
                $info,
294
                $path,
295
                $result
296
            );
297
298
            if ($completed instanceof ExtendedPromiseInterface) {
299
                return $completed->then(null, function ($error) use ($fieldNodes, $path) {
300
                    if ($error instanceof \Exception) {
301
                        $this->handleError(
302
                            $this->buildLocatedError($error, $fieldNodes, $path)
303
                        );
304
                    } else {
305
                        $this->handleError(
306
                            $this->buildLocatedError(
307
                                new ExecutionException($error ?? 'An unknown error occurred.'),
308
                                $fieldNodes,
309
                                $path
310
                            )
311
                        );
312
                    }
313
314
                    return new FulfilledPromise(null);
315
                });
316
            }
317
318
            return $completed;
319
        } catch (\Throwable $ex) {
320
            $this->handleError($this->buildLocatedError($ex, $fieldNodes, $path));
321
            return null;
322
        }
323
    }
324
325
    /**
326
     * @param TypeInterface $fieldType
327
     * @param FieldNode[]   $fieldNodes
328
     * @param ResolveInfo   $info
329
     * @param array         $path
330
     * @param mixed         $result
331
     *
332
     * @return array|mixed
333
     * @throws \Throwable
334
     */
335
    public function completeValueWithLocatedError(
336
        TypeInterface $fieldType,
337
        array $fieldNodes,
338
        ResolveInfo $info,
339
        array $path,
340
        $result
341
    ) {
342
        try {
343
            $completed = $this->completeValue(
344
                $fieldType,
345
                $fieldNodes,
346
                $info,
347
                $path,
348
                $result
349
            );
350
351
            return $completed;
352
        } catch (\Throwable $ex) {
353
            throw $this->buildLocatedError($ex, $fieldNodes, $path);
354
        }
355
    }
356
357
    /**
358
     * Implements the "Evaluating selection sets" section of the spec for "read" mode.
359
     *
360
     * @param ObjectType $objectType
361
     * @param mixed      $rootValue
362
     * @param array      $path
363
     * @param array      $fields
364
     *
365
     * @return array
366
     * @throws ExecutionException
367
     * @throws \Throwable
368
     */
369
    protected function executeFields(
370
        ObjectType $objectType,
371
        $rootValue,
372
        array $path,
373
        array $fields
374
    ): array {
375
        $finalResults       = [];
376
        $doesContainPromise = false;
377
378
        foreach ($fields as $fieldName => $fieldNodes) {
379
            $fieldPath   = $path;
380
            $fieldPath[] = $fieldName;
381
382
            try {
383
                $result = $this->resolveField($objectType, $rootValue, $fieldNodes, $fieldPath);
384
            } catch (UndefinedException $ex) {
385
                continue;
386
            }
387
388
            $doesContainPromise = $doesContainPromise || $result instanceof ExtendedPromiseInterface;
389
390
            $finalResults[$fieldName] = $result;
391
        }
392
393
        if ($doesContainPromise) {
394
            $keys    = \array_keys($finalResults);
395
            $promise = promiseAll(\array_values($finalResults));
396
397
            $promise->then(function ($values) use ($keys, &$finalResults) {
398
                /** @noinspection ForeachSourceInspection */
399
                foreach ($values as $i => $value) {
400
                    $finalResults[$keys[$i]] = $value;
401
                }
402
            });
403
        }
404
405
        return $finalResults;
406
    }
407
408
    /**
409
     * @param ObjectType  $parentType
410
     * @param mixed       $rootValue
411
     * @param FieldNode[] $fieldNodes
412
     * @param array       $path
413
     *
414
     * @return array|mixed|null
415
     * @throws UndefinedException
416
     * @throws \Throwable
417
     */
418
    protected function resolveField(
419
        ObjectType $parentType,
420
        $rootValue,
421
        array $fieldNodes,
422
        array $path
423
    ) {
424
        /** @var FieldNode $fieldNode */
425
        $fieldNode = $fieldNodes[0];
426
427
        $field = $this->getFieldDefinition($this->context->getSchema(), $parentType, $fieldNode->getNameValue());
428
429
        if (null === $field) {
430
            throw new UndefinedException('Undefined field definition.');
431
        }
432
433
        $info = $this->createResolveInfo($fieldNodes, $fieldNode, $field, $parentType, $path, $this->context);
434
435
        $resolveCallback = $this->determineResolveCallback($field, $parentType);
436
437
        $result = $this->resolveFieldValueOrError(
438
            $field,
439
            $fieldNode,
440
            $resolveCallback,
441
            $rootValue,
442
            $this->context,
443
            $info
444
        );
445
446
        $result = $this->completeValueCatchingError(
447
            $field->getType(),
448
            $fieldNodes,
449
            $info,
450
            $path,
451
            $result
452
        );
453
454
        return $result;
455
    }
456
457
    /**
458
     * @param Field      $field
459
     * @param ObjectType $objectType
460
     *
461
     * @return callable|mixed|null
462
     */
463
    protected function determineResolveCallback(Field $field, ObjectType $objectType)
464
    {
465
        if ($field->hasResolveCallback()) {
466
            return $field->getResolveCallback();
467
        }
468
469
        if ($objectType->hasResolveCallback()) {
470
            return $objectType->getResolveCallback();
471
        }
472
473
        return $this->context->getFieldResolver() ?? self::$defaultFieldResolver;
474
    }
475
476
    /**
477
     * @param TypeInterface $returnType
478
     * @param FieldNode[]   $fieldNodes
479
     * @param ResolveInfo   $info
480
     * @param array         $path
481
     * @param mixed         $result
482
     *
483
     * @return array|mixed
484
     * @throws InvariantException
485
     * @throws InvalidTypeException
486
     * @throws ExecutionException
487
     * @throws \Throwable
488
     */
489
    protected function completeValue(
490
        TypeInterface $returnType,
491
        array $fieldNodes,
492
        ResolveInfo $info,
493
        array $path,
494
        &$result
495
    ) {
496
        if ($result instanceof ExtendedPromiseInterface) {
497
            return $result->then(function (&$value) use ($returnType, $fieldNodes, $info, $path) {
498
                return $this->completeValue($returnType, $fieldNodes, $info, $path, $value);
499
            });
500
        }
501
502
        if ($result instanceof \Throwable) {
503
            throw $result;
504
        }
505
506
        // If result is null-like, return null.
507
        if (null === $result) {
508
            return null;
509
        }
510
511
        if ($returnType instanceof NonNullType) {
512
            $completed = $this->completeValue(
513
                $returnType->getOfType(),
514
                $fieldNodes,
515
                $info,
516
                $path,
517
                $result
518
            );
519
520
            if ($completed === null) {
521
                throw new ExecutionException(
522
                    \sprintf(
523
                        'Cannot return null for non-nullable field %s.%s.',
524
                        $info->getParentType(),
525
                        $info->getFieldName()
526
                    )
527
                );
528
            }
529
530
            return $completed;
531
        }
532
533
        // If field type is List, complete each item in the list with the inner type
534
        if ($returnType instanceof ListType) {
535
            return $this->completeListValue($returnType, $fieldNodes, $info, $path, $result);
536
        }
537
538
        // If field type is Scalar or Enum, serialize to a valid value, returning
539
        // null if serialization is not possible.
540
        if ($returnType instanceof LeafTypeInterface) {
541
            return $this->completeLeafValue($returnType, $result);
542
        }
543
544
        // TODO: Make a function for checking abstract type?
545
        if ($returnType instanceof InterfaceType || $returnType instanceof UnionType) {
546
            return $this->completeAbstractValue($returnType, $fieldNodes, $info, $path, $result);
547
        }
548
549
        // Field type must be Object, Interface or Union and expect sub-selections.
550
        if ($returnType instanceof ObjectType) {
551
            return $this->completeObjectValue($returnType, $fieldNodes, $info, $path, $result);
552
        }
553
554
        throw new ExecutionException("Cannot complete value of unexpected type \"{$returnType}\".");
555
    }
556
557
    /**
558
     * @param AbstractTypeInterface $returnType
559
     * @param FieldNode[]           $fieldNodes
560
     * @param ResolveInfo           $info
561
     * @param array                 $path
562
     * @param mixed                 $result
563
     *
564
     * @return array|PromiseInterface
565
     * @throws ExecutionException
566
     * @throws InvalidTypeException
567
     * @throws InvariantException
568
     * @throws \Throwable
569
     */
570
    protected function completeAbstractValue(
571
        AbstractTypeInterface $returnType,
572
        array $fieldNodes,
573
        ResolveInfo $info,
574
        array $path,
575
        &$result
576
    ) {
577
        $runtimeType = $returnType->resolveType($result, $this->context->getContextValue(), $info);
578
579
        if (null === $runtimeType) {
580
            // TODO: Display warning
581
            $runtimeType = $this->defaultTypeResolver($result, $this->context->getContextValue(), $info, $returnType);
582
        }
583
584
        if ($runtimeType instanceof ExtendedPromiseInterface) {
585
            return $runtimeType->then(function ($resolvedRuntimeType) use (
586
                $returnType,
587
                $fieldNodes,
588
                $info,
589
                $path,
590
                &$result
591
            ) {
592
                return $this->completeObjectValue(
593
                    $this->ensureValidRuntimeType($resolvedRuntimeType, $returnType, $info, $result),
594
                    $fieldNodes,
595
                    $info,
596
                    $path,
597
                    $result
598
                );
599
            });
600
        }
601
602
        return $this->completeObjectValue(
603
            $this->ensureValidRuntimeType($runtimeType, $returnType, $info, $result),
604
            $fieldNodes,
605
            $info,
606
            $path,
607
            $result
608
        );
609
    }
610
611
    /**
612
     * @param NamedTypeInterface|string $runtimeTypeOrName
613
     * @param NamedTypeInterface        $returnType
614
     * @param ResolveInfo               $info
615
     * @param mixed                     $result
616
     *
617
     * @return TypeInterface|ObjectType|null
618
     * @throws ExecutionException
619
     * @throws InvariantException
620
     */
621
    protected function ensureValidRuntimeType(
622
        $runtimeTypeOrName,
623
        NamedTypeInterface $returnType,
624
        ResolveInfo $info,
625
        &$result
626
    ) {
627
        /** @var NamedTypeInterface $runtimeType */
628
        $runtimeType = \is_string($runtimeTypeOrName)
629
            ? $this->context->getSchema()->getType($runtimeTypeOrName)
630
            : $runtimeTypeOrName;
631
632
        $runtimeTypeName = $runtimeType->getName();
633
        $returnTypeName  = $returnType->getName();
634
635
        if (!$runtimeType instanceof ObjectType) {
636
            $parentTypeName = $info->getParentType()->getName();
637
            $fieldName      = $info->getFieldName();
638
639
            throw new ExecutionException(
640
                \sprintf(
641
                    'Abstract type %s must resolve to an Object type at runtime for field %s.%s ' .
642
                    'with value "%s", received "%s".',
643
                    $returnTypeName,
644
                    $parentTypeName,
645
                    $fieldName,
646
                    $result,
647
                    $runtimeTypeName
648
                )
649
            );
650
        }
651
652
        if (!$this->context->getSchema()->isPossibleType($returnType, $runtimeType)) {
653
            throw new ExecutionException(
654
                \sprintf('Runtime Object type "%s" is not a possible type for "%s".', $runtimeTypeName, $returnTypeName)
655
            );
656
        }
657
658
        if ($runtimeType !== $this->context->getSchema()->getType($runtimeType->getName())) {
0 ignored issues
show
introduced by
The condition $runtimeType is always true. If $runtimeType can have other possible types, add them to src/Execution/Executor.php:627
Loading history...
659
            throw new ExecutionException(
660
                \sprintf(
661
                    'Schema must contain unique named types but contains multiple types named "%s". ' .
662
                    'Make sure that `resolveType` function of abstract type "%s" returns the same ' .
663
                    'type instance as referenced anywhere else within the schema.',
664
                    $runtimeTypeName,
665
                    $returnTypeName
666
                )
667
            );
668
        }
669
670
        return $runtimeType;
671
    }
672
673
    /**
674
     * @param mixed                 $value
675
     * @param mixed                 $context
676
     * @param ResolveInfo           $info
677
     * @param AbstractTypeInterface $abstractType
678
     *
679
     * @return NamedTypeInterface|mixed|null
680
     * @throws InvariantException
681
     */
682
    protected function defaultTypeResolver(
683
        $value,
684
        $context,
685
        ResolveInfo $info,
686
        AbstractTypeInterface $abstractType
687
    ) {
688
        if (\is_array($value) && isset($value['__typename'])) {
689
            return $value['__typename'];
690
        }
691
692
        /** @var ObjectType[] $possibleTypes */
693
        $possibleTypes           = $info->getSchema()->getPossibleTypes($abstractType);
694
        $promisedIsTypeOfResults = [];
695
696
        foreach ($possibleTypes as $index => $type) {
697
            $isTypeOfResult = $type->isTypeOf($value, $context, $info);
698
699
            if ($isTypeOfResult instanceof ExtendedPromiseInterface) {
700
                $promisedIsTypeOfResults[$index] = $isTypeOfResult;
701
                continue;
702
            }
703
704
            if ($isTypeOfResult === true) {
705
                return $type;
706
            }
707
708
            if (\is_array($value)) {
709
                // TODO: Make `type` configurable
710
                /** @noinspection NestedPositiveIfStatementsInspection */
711
                if (isset($value['type']) && $value['type'] === $type->getName()) {
712
                    return $type;
713
                }
714
            }
715
        }
716
717
        if (!empty($promisedIsTypeOfResults)) {
718
            return promiseAll($promisedIsTypeOfResults)
719
                ->then(function ($isTypeOfResults) use ($possibleTypes) {
720
                    /** @noinspection ForeachSourceInspection */
721
                    foreach ($isTypeOfResults as $index => $result) {
722
                        if ($result) {
723
                            return $possibleTypes[$index];
724
                        }
725
                    }
726
727
                    return null;
728
                });
729
        }
730
731
        return null;
732
    }
733
734
    /**
735
     * @param ListType    $returnType
736
     * @param FieldNode[] $fieldNodes
737
     * @param ResolveInfo $info
738
     * @param array       $path
739
     * @param mixed       $result
740
     *
741
     * @return array|\React\Promise\Promise
742
     * @throws \Throwable
743
     */
744
    protected function completeListValue(
745
        ListType $returnType,
746
        array $fieldNodes,
747
        ResolveInfo $info,
748
        array $path,
749
        &$result
750
    ) {
751
        $itemType = $returnType->getOfType();
752
753
        $completedItems     = [];
754
        $doesContainPromise = false;
755
756
        if (!\is_array($result) && !($result instanceof \Traversable)) {
757
            /** @noinspection ThrowRawExceptionInspection */
758
            throw new \Exception(
759
                \sprintf(
760
                    'Expected Array or Traversable, but did not find one for field %s.%s.',
761
                    $info->getParentType()->getName(),
762
                    $info->getFieldName()
763
                )
764
            );
765
        }
766
767
        foreach ($result as $key => $item) {
768
            $fieldPath          = $path;
769
            $fieldPath[]        = $key;
770
            $completedItem      = $this->completeValueCatchingError($itemType, $fieldNodes, $info, $fieldPath, $item);
771
            $completedItems[]   = $completedItem;
772
            $doesContainPromise = $doesContainPromise || $completedItem instanceof ExtendedPromiseInterface;
773
        }
774
775
        return $doesContainPromise
776
            ? promiseAll($completedItems)
777
            : $completedItems;
778
    }
779
780
    /**
781
     * @param LeafTypeInterface|SerializableTypeInterface $returnType
782
     * @param mixed                                       $result
783
     *
784
     * @return mixed
785
     * @throws ExecutionException
786
     */
787
    protected function completeLeafValue($returnType, &$result)
788
    {
789
        $serializedResult = $returnType->serialize($result);
0 ignored issues
show
Bug introduced by
The method serialize() does not exist on Digia\GraphQL\Type\Definition\LeafTypeInterface. Since it exists in all sub-types, consider adding an abstract or default implementation to Digia\GraphQL\Type\Definition\LeafTypeInterface. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

789
        /** @scrutinizer ignore-call */ 
790
        $serializedResult = $returnType->serialize($result);
Loading history...
790
791
        if ($serializedResult === null) {
792
            // TODO: Make a method for this type of exception
793
            throw new ExecutionException(
794
                \sprintf('Expected value of type "%s" but received: %s.', (string)$returnType, toString($result))
795
            );
796
        }
797
798
        return $serializedResult;
799
    }
800
801
    /**
802
     * @param ObjectType  $returnType
803
     * @param array       $fieldNodes
804
     * @param ResolveInfo $info
805
     * @param array       $path
806
     * @param mixed       $result
807
     *
808
     * @return array
809
     * @throws ExecutionException
810
     * @throws InvalidTypeException
811
     * @throws InvariantException
812
     * @throws \Throwable
813
     */
814
    protected function completeObjectValue(
815
        ObjectType $returnType,
816
        array $fieldNodes,
817
        ResolveInfo $info,
818
        array $path,
819
        &$result
820
    ): array {
821
        if (null !== $returnType->getIsTypeOf()) {
0 ignored issues
show
introduced by
The condition null !== $returnType->getIsTypeOf() is always true.
Loading history...
822
            $isTypeOf = $returnType->isTypeOf($result, $this->context->getContextValue(), $info);
823
824
            // TODO: Check for promise?
825
            if (!$isTypeOf) {
826
                throw new ExecutionException(
827
                    sprintf('Expected value of type "%s" but received: %s.', (string)$returnType, toString($result))
828
                );
829
            }
830
        }
831
832
        return $this->executeSubFields($returnType, $fieldNodes, $path, $result);
833
    }
834
835
    /**
836
     * @param Field            $field
837
     * @param FieldNode        $fieldNode
838
     * @param callable         $resolveCallback
839
     * @param mixed            $rootValue
840
     * @param ExecutionContext $context
841
     * @param ResolveInfo      $info
842
     *
843
     * @return array|\Throwable
844
     */
845
    protected function resolveFieldValueOrError(
846
        Field $field,
847
        FieldNode $fieldNode,
848
        ?callable $resolveCallback,
849
        $rootValue,
850
        ExecutionContext $context,
851
        ResolveInfo $info
852
    ) {
853
        try {
854
            $result = $resolveCallback(
855
                $rootValue,
856
                coerceArgumentValues($field, $fieldNode, $context->getVariableValues()),
857
                $context->getContextValue(),
858
                $info
859
            );
860
        } catch (\Throwable $error) {
861
            return $error;
862
        }
863
864
        return $result;
865
    }
866
867
    /**
868
     * @param ObjectType  $returnType
869
     * @param FieldNode[] $fieldNodes
870
     * @param array       $path
871
     * @param mixed       $result
872
     *
873
     * @return array
874
     * @throws ExecutionException
875
     * @throws InvalidTypeException
876
     * @throws InvariantException
877
     * @throws \Throwable
878
     */
879
    protected function executeSubFields(
880
        ObjectType $returnType,
881
        array $fieldNodes,
882
        array $path,
883
        &$result
884
    ): array {
885
        $subFields            = [];
886
        $visitedFragmentNames = [];
887
888
        foreach ($fieldNodes as $fieldNode) {
889
            if (null !== $fieldNode->getSelectionSet()) {
890
                $subFields = $this->fieldCollector->collectFields(
891
                    $returnType,
892
                    $fieldNode->getSelectionSet(),
893
                    $subFields,
894
                    $visitedFragmentNames
895
                );
896
            }
897
        }
898
899
        if (!empty($subFields)) {
900
            return $this->executeFields($returnType, $result, $path, $subFields);
901
        }
902
903
        return $result;
904
    }
905
906
    /**
907
     * @param \Throwable $originalException
908
     * @param array      $nodes
909
     * @param array      $path
910
     *
911
     * @return ExecutionException
912
     */
913
    protected function buildLocatedError(
914
        \Throwable $originalException,
915
        array $nodes = [],
916
        array $path = []
917
    ): ExecutionException {
918
        return new ExecutionException(
919
            $originalException->getMessage(),
920
            $originalException instanceof GraphQLException
921
                ? $originalException->getNodes()
922
                : $nodes,
923
            $originalException instanceof GraphQLException
924
                ? $originalException->getSource()
925
                : null,
926
            $originalException instanceof GraphQLException
927
                ? $originalException->getPositions()
928
                : null,
929
            $originalException instanceof GraphQLException
930
                ? ($originalException->getPath() ?? $path)
931
                : $path,
932
            null,
933
            $originalException
934
        );
935
    }
936
937
    /**
938
     * @param FieldNode[]      $fieldNodes
939
     * @param FieldNode        $fieldNode
940
     * @param Field            $field
941
     * @param ObjectType       $parentType
942
     * @param array|null       $path
943
     * @param ExecutionContext $context
944
     *
945
     * @return ResolveInfo
946
     */
947
    protected function createResolveInfo(
948
        array $fieldNodes,
949
        FieldNode $fieldNode,
950
        Field $field,
951
        ObjectType $parentType,
952
        ?array $path,
953
        ExecutionContext $context
954
    ): ResolveInfo {
955
        return new ResolveInfo(
956
            $fieldNode->getNameValue(),
957
            $fieldNodes,
958
            $field->getType(),
959
            $parentType,
960
            $path,
961
            $context->getSchema(),
962
            $context->getFragments(),
963
            $context->getRootValue(),
964
            $context->getOperation(),
965
            $context->getVariableValues()
966
        );
967
    }
968
969
    /**
970
     * @param ExecutionException $error
971
     */
972
    protected function handleError(ExecutionException $error)
973
    {
974
        if (null !== $this->errorHandler) {
975
            $this->errorHandler->handleError($error);
976
        }
977
978
        $this->context->addError($error);
979
    }
980
981
    /**
982
     * Try to resolve a field without any field resolver function.
983
     *
984
     * @param array|object $rootValue
985
     * @param array        $arguments
986
     * @param mixed        $contextValues
987
     * @param ResolveInfo  $info
988
     *
989
     * @return mixed|null
990
     */
991
    public static function defaultFieldResolver($rootValue, array $arguments, $contextValues, ResolveInfo $info)
992
    {
993
        $fieldName = $info->getFieldName();
994
        $property  = null;
995
996
        if (\is_array($rootValue) && isset($rootValue[$fieldName])) {
997
            $property = $rootValue[$fieldName];
998
        }
999
1000
        if (\is_object($rootValue)) {
1001
            $getter = 'get' . \ucfirst($fieldName);
1002
            if (\method_exists($rootValue, $getter)) {
1003
                $property = $rootValue->{$getter}();
1004
            } elseif (\method_exists($rootValue, $fieldName)) {
1005
                $property = $rootValue->{$fieldName}($rootValue, $arguments, $contextValues, $info);
1006
            } elseif (\property_exists($rootValue, $fieldName)) {
1007
                $property = $rootValue->{$fieldName};
1008
            }
1009
        }
1010
1011
        return $property instanceof \Closure
1012
            ? $property($rootValue, $arguments, $contextValues, $info)
1013
            : $property;
1014
    }
1015
}
1016