Passed
Push — master ( aebe7d...784c11 )
by Christoffer
02:24
created

ScalarLeafsRule   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 33
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 6
dl 0
loc 33
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
B enterNode() 0 28 6
1
<?php
2
3
namespace Digia\GraphQL\Validation\Rule;
4
5
use Digia\GraphQL\Error\ValidationException;
6
use Digia\GraphQL\Language\Node\FieldNode;
7
use Digia\GraphQL\Language\Node\NodeInterface;
8
use Digia\GraphQL\Type\Definition\LeafTypeInterface;
9
use function Digia\GraphQL\Type\getNamedType;
10
use function Digia\GraphQL\Validation\noSubselectionAllowedMessage;
11
use function Digia\GraphQL\Validation\requiresSubselectionMessage;
12
13
/**
14
 * Scalar leafs
15
 *
16
 * A GraphQL document is valid only if all leaf fields (fields without
17
 * sub selections) are of scalar or enum types.
18
 */
19
class ScalarLeafsRule extends AbstractRule
20
{
21
    /**
22
     * @inheritdoc
23
     */
24
    public function enterNode(NodeInterface $node): ?NodeInterface
25
    {
26
        if ($node instanceof FieldNode) {
27
            $type         = $this->validationContext->getType();
28
            $selectionSet = $node->getSelectionSet();
29
30
            if (null !== $type) {
31
                if (getNamedType($type) instanceof LeafTypeInterface) {
32
                    if (null !== $selectionSet) {
33
                        $this->validationContext->reportError(
34
                            new ValidationException(
35
                                noSubselectionAllowedMessage((string)$node, (string)$type),
36
                                [$selectionSet]
37
                            )
38
                        );
39
                    }
40
                } elseif (null === $selectionSet) {
41
                    $this->validationContext->reportError(
42
                        new ValidationException(
43
                            requiresSubselectionMessage((string)$node, (string)$type),
44
                            [$node]
45
                        )
46
                    );
47
                }
48
            }
49
        }
50
51
        return $node;
52
    }
53
}
54