Completed
Pull Request — master (#45)
by Christoffer
02:13
created

KnownTypeNamesRule   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 28
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
dl 0
loc 28
rs 10
c 0
b 0
f 0
wmc 7

1 Method

Rating   Name   Duplication   Size   Complexity  
C enterNode() 0 23 7
1
<?php
2
3
namespace Digia\GraphQL\Validation\Rule;
4
5
use Digia\GraphQL\Error\ValidationException;
6
use Digia\GraphQL\Language\AST\Node\InputObjectTypeDefinitionNode;
7
use Digia\GraphQL\Language\AST\Node\InterfaceTypeDefinitionNode;
8
use Digia\GraphQL\Language\AST\Node\NamedTypeNode;
9
use Digia\GraphQL\Language\AST\Node\NodeInterface;
10
use Digia\GraphQL\Language\AST\Node\ObjectTypeDefinitionNode;
11
use Digia\GraphQL\Language\AST\Node\UnionTypeDefinitionNode;
12
use function Digia\GraphQL\Util\suggestionList;
13
14
/**
15
 * Known type names
16
 *
17
 * A GraphQL document is only valid if referenced types (specifically
18
 * variable definitions and fragment conditions) are defined by the type schema.
19
 */
20
class KnownTypeNamesRule extends AbstractRule
21
{
22
    /**
23
     * @inheritdoc
24
     */
25
    public function enterNode(NodeInterface $node): ?NodeInterface
26
    {
27
        if ($node instanceof ObjectTypeDefinitionNode || $node instanceof InterfaceTypeDefinitionNode || $node instanceof UnionTypeDefinitionNode || $node instanceof InputObjectTypeDefinitionNode) {
28
            // TODO: when validating IDL, re-enable these. Experimental version does not add unreferenced types, resulting in false-positive errors. Squelched errors for now.
29
            return null;
30
        }
31
32
        if ($node instanceof NamedTypeNode) {
33
            $schema   = $this->validationContext->getSchema();
34
            $typeName = $node->getNameValue();
35
            $type     = $schema->getType($typeName);
36
37
            if (null === $type) {
38
                $this->validationContext->reportError(
39
                    new ValidationException(
40
                        unknownTypeMessage($typeName, suggestionList($typeName, array_keys($schema->getTypeMap()))),
41
                        [$node]
42
                    )
43
                );
44
            }
45
        }
46
47
        return $node;
48
    }
49
}
50