Completed
Pull Request — master (#226)
by Christoffer
02:58
created

RootTypesRule::validateRootType()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 7
nc 2
nop 2
dl 0
loc 13
rs 9.2
c 0
b 0
f 0
1
<?php
2
3
namespace Digia\GraphQL\Schema\Validation\Rule;
4
5
use Digia\GraphQL\Error\SchemaValidationException;
6
use Digia\GraphQL\Language\Node\NodeInterface;
7
use Digia\GraphQL\Language\Node\OperationTypeDefinitionNode;
8
use Digia\GraphQL\Language\Node\SchemaDefinitionNode;
9
use Digia\GraphQL\Schema\Schema;
10
use Digia\GraphQL\Type\Definition\NamedTypeInterface;
11
use Digia\GraphQL\Type\Definition\ObjectType;
12
use function Digia\GraphQL\Util\find;
13
14
class RootTypesRule extends AbstractRule
15
{
16
    /**
17
     * @inheritdoc
18
     */
19
    public function evaluate(): void
20
    {
21
        $schema = $this->context->getSchema();
22
23
        $rootTypes = [
24
            'query'        => $schema->getQueryType(),
25
            'mutation'     => $schema->getMutationType(),
26
            'subscription' => $schema->getSubscriptionType(),
27
        ];
28
29
        foreach ($rootTypes as $operation => $rootType) {
30
            $this->validateRootType($rootType, $operation);
31
        }
32
    }
33
34
    /**
35
     * @param NamedTypeInterface|ObjectType|null $rootType
36
     * @param string                             $operation
37
     */
38
    protected function validateRootType(?NamedTypeInterface $rootType, string $operation): void
39
    {
40
        $schema = $this->context->getSchema();
41
42
        if ($operation === 'query' && null === $rootType) {
43
            $this->context->reportError(
44
                new SchemaValidationException(
45
                    \sprintf('%s root type must be provided.', \ucfirst($operation)),
46
                    $schema->hasAstNode() ? [$schema->getAstNode()] : null
47
                )
48
            );
49
50
            return;
51
        }
52
    }
53
}
54