Passed
Push — master ( 3ec7eb...90aa38 )
by Christoffer
02:15
created

LoneAnonymousOperationRule::enterNode()   B

Complexity

Conditions 5
Paths 6

Size

Total Lines 17
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 8
nc 6
nop 1
dl 0
loc 17
rs 8.8571
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\DocumentNode;
7
use Digia\GraphQL\Language\Node\NodeInterface;
8
use Digia\GraphQL\Language\Node\OperationDefinitionNode;
9
use function Digia\GraphQL\Validation\anonymousOperationNotAloneMessage;
10
11
/**
12
 * Lone anonymous operation
13
 *
14
 * A GraphQL document is only valid when it contains an anonymous operation
15
 * (the query short-hand) that it contains only that one operation definition.
16
 */
17
class LoneAnonymousOperationRule extends AbstractRule
18
{
19
    /**
20
     * @var int
21
     */
22
    protected $operationCount = 0;
23
24
    /**
25
     * @inheritdoc
26
     */
27
    public function enterNode(NodeInterface $node): ?NodeInterface
28
    {
29
        if ($node instanceof DocumentNode) {
30
            $this->operationCount = \count(array_filter($node->getDefinitions(), function ($definition) {
31
                return $definition instanceof OperationDefinitionNode;
32
            }));
33
        }
34
35
        if ($node instanceof OperationDefinitionNode) {
36
            if (null === $node->getName() && $this->operationCount > 1) {
37
                $this->validationContext->reportError(
38
                    new ValidationException(anonymousOperationNotAloneMessage(), [$node])
39
                );
40
            }
41
        }
42
43
        return $node;
44
    }
45
}
46