Passed
Pull Request — master (#226)
by Christoffer
02:35
created

ExecutableDefinitionsRule::getDefinitionName()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 5
nc 3
nop 1
dl 0
loc 9
rs 9.6666
c 0
b 0
f 0
1
<?php
2
3
namespace Digia\GraphQL\Validation\Rule;
4
5
use Digia\GraphQL\Error\ValidationException;
6
use Digia\GraphQL\Language\Node\DefinitionNodeInterface;
7
use Digia\GraphQL\Language\Node\DocumentNode;
8
use Digia\GraphQL\Language\Node\ExecutableDefinitionNodeInterface;
9
use Digia\GraphQL\Language\Node\NameAwareInterface;
10
use Digia\GraphQL\Language\Node\NodeInterface;
11
use Digia\GraphQL\Language\Node\SchemaDefinitionNode;
12
use function Digia\GraphQL\Validation\nonExecutableDefinitionMessage;
13
14
/**
15
 * Executable definitions
16
 *
17
 * A GraphQL document is only valid for execution if all definitions are either
18
 * operation or fragment definitions.
19
 */
20
class ExecutableDefinitionsRule extends AbstractRule
21
{
22
    /**
23
     * @inheritdoc
24
     */
25
    protected function enterDocument(DocumentNode $node): ?NodeInterface
26
    {
27
        foreach ($node->getDefinitions() as $definition) {
28
            if (!$definition instanceof ExecutableDefinitionNodeInterface) {
29
                $this->context->reportError(
30
                    new ValidationException(
31
                        nonExecutableDefinitionMessage($this->getDefinitionName($definition)),
32
                        [$definition]
33
                    )
34
                );
35
            }
36
        }
37
38
        return $node;
39
    }
40
41
    /**
42
     * @param NodeInterface $node
43
     * @return string
44
     */
45
    protected function getDefinitionName(NodeInterface $node): string
46
    {
47
        if ($node instanceof SchemaDefinitionNode) {
48
            return 'schema';
49
        }
50
51
        return $node instanceof NameAwareInterface
0 ignored issues
show
Bug Best Practice introduced by
The expression return $node instanceof ...NameValue() : 'unknown' could return the type null which is incompatible with the type-hinted return string. Consider adding an additional type-check to rule them out.
Loading history...
52
            ? $node->getNameValue()
53
            : 'unknown';
54
    }
55
}
56