Completed
Pull Request — master (#92)
by Christoffer
02:21
created

SingleFieldSubscriptionsRule::enterNode()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 18
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 10
nc 4
nop 1
1
<?php
2
3
namespace Digia\GraphQL\Validation\Rule;
4
5
use Digia\GraphQL\Error\ValidationException;
6
use Digia\GraphQL\Language\Node\NodeInterface;
7
use Digia\GraphQL\Language\Node\OperationDefinitionNode;
8
use function Digia\GraphQL\Validation\singleFieldOnlyMessage;
9
10
/**
11
 * Subscriptions must only include one field.
12
 *
13
 * A GraphQL subscription is valid only if it contains a single root field.
14
 */
15
class SingleFieldSubscriptionsRule extends AbstractRule
16
{
17
    /**
18
     * @inheritdoc
19
     */
20
    public function enterNode(NodeInterface $node): ?NodeInterface
21
    {
22
        if ($node instanceof OperationDefinitionNode && $node->getOperation() === 'subscription') {
23
            $selectionSet = $node->getSelectionSet();
24
            if (null !== $selectionSet) {
25
                $selections = $selectionSet->getSelections();
26
                if (\count($selections) !== 1) {
27
                    $this->validationContext->reportError(
28
                        new ValidationException(
29
                            singleFieldOnlyMessage((string)$node),
30
                            \array_slice($selections, 1)
31
                        )
32
                    );
33
                }
34
            }
35
        }
36
37
        return $node;
38
    }
39
}
40