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

LoneAnonymousOperationRule   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 27
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
dl 0
loc 27
rs 10
c 0
b 0
f 0
wmc 5

1 Method

Rating   Name   Duplication   Size   Complexity  
B enterNode() 0 17 5
1
<?php
2
3
namespace Digia\GraphQL\Validation\Rule;
4
5
use Digia\GraphQL\Error\ValidationException;
6
use Digia\GraphQL\Language\AST\Node\DocumentNode;
7
use Digia\GraphQL\Language\AST\Node\NodeInterface;
8
use Digia\GraphQL\Language\AST\Node\OperationDefinitionNode;
9
10
/**
11
 * Lone anonymous operation
12
 *
13
 * A GraphQL document is only valid if when it contains an anonymous operation
14
 * (the query short-hand) that it contains only that one operation definition.
15
 */
16
class LoneAnonymousOperationRule extends AbstractRule
17
{
18
    /**
19
     * @var int
20
     */
21
    protected $operationCount = 0;
22
23
    /**
24
     * @inheritdoc
25
     */
26
    public function enterNode(NodeInterface $node): ?NodeInterface
27
    {
28
        if ($node instanceof DocumentNode) {
29
            $this->operationCount = \count(array_filter($node->getDefinitions(), function ($definition) {
30
                return $definition instanceof OperationDefinitionNode;
31
            }));
32
        }
33
34
        if ($node instanceof OperationDefinitionNode) {
35
            if (null === $node->getName() && $this->operationCount > 1) {
36
                $this->context->reportError(
37
                    new ValidationException(anonymousOperationNotAloneMessage(), [$node])
38
                );
39
            }
40
        }
41
42
        return $node;
43
    }
44
}
45