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

SingleFieldSubscriptionsRule   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 23
Duplicated Lines 0 %

Importance

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

1 Method

Rating   Name   Duplication   Size   Complexity  
B enterNode() 0 18 5
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