Completed
Pull Request — master (#110)
by Christoffer
02:25
created

ScalarLeafsRule::enterField()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 26
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 26
rs 8.439
c 0
b 0
f 0
cc 5
eloc 15
nc 5
nop 1
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
    protected function enterField(FieldNode $node): ?NodeInterface
25
    {
26
        $type         = $this->context->getType();
27
        $selectionSet = $node->getSelectionSet();
28
29
        if (null !== $type) {
30
            if (getNamedType($type) instanceof LeafTypeInterface) {
31
                if (null !== $selectionSet) {
32
                    $this->context->reportError(
33
                        new ValidationException(
34
                            noSubselectionAllowedMessage((string)$node, (string)$type),
35
                            [$selectionSet]
36
                        )
37
                    );
38
                }
39
            } elseif (null === $selectionSet) {
40
                $this->context->reportError(
41
                    new ValidationException(
42
                        requiresSubselectionMessage((string)$node, (string)$type),
43
                        [$node]
44
                    )
45
                );
46
            }
47
        }
48
49
        return $node;
50
    }
51
}
52