Issues (167)

src/Validation/Rule/NoUnusedFragmentsRule.php (1 issue)

Labels
Severity
1
<?php
2
3
namespace Digia\GraphQL\Validation\Rule;
4
5
use Digia\GraphQL\Language\Node\DocumentNode;
6
use Digia\GraphQL\Language\Node\FragmentDefinitionNode;
7
use Digia\GraphQL\Language\Node\OperationDefinitionNode;
8
use Digia\GraphQL\Language\Visitor\VisitorResult;
9
use Digia\GraphQL\Validation\ValidationException;
10
use function Digia\GraphQL\Validation\unusedFragmentMessage;
11
12
/**
13
 * No unused fragments
14
 *
15
 * A GraphQL document is only valid if all fragment definitions are spread
16
 * within operations, or spread within other fragments spread within operations.
17
 */
18
class NoUnusedFragmentsRule extends AbstractRule
19
{
20
    /**
21
     * @var OperationDefinitionNode[]
22
     */
23
    protected $operationDefinitions = [];
24
25
    /**
26
     * @var FragmentDefinitionNode[]
27
     */
28
    protected $fragmentDefinitions = [];
29
30
    /**
31
     * @inheritdoc
32
     */
33
    protected function enterOperationDefinition(OperationDefinitionNode $node): VisitorResult
34
    {
35
        $this->operationDefinitions[] = $node;
36
37
        return new VisitorResult(null);
38
    }
39
40
    /**
41
     * @inheritdoc
42
     */
43
    protected function enterFragmentDefinition(FragmentDefinitionNode $node): VisitorResult
44
    {
45
        $this->fragmentDefinitions[] = $node;
46
47
        return new VisitorResult(null);
48
    }
49
50
    /**
51
     * @inheritdoc
52
     */
53
    protected function leaveDocument(DocumentNode $node): VisitorResult
54
    {
55
        $fragmentNamesUsed = [];
56
57
        foreach ($this->operationDefinitions as $operationDefinition) {
58
            foreach ($this->context->getRecursivelyReferencedFragments($operationDefinition) as $fragmentDefinition) {
59
                $fragmentNamesUsed[$fragmentDefinition->getNameValue()] = true;
60
            }
61
        }
62
63
        foreach ($this->fragmentDefinitions as $fragmentDefinition) {
64
            $fragmentName = $fragmentDefinition->getNameValue();
65
66
            if (!isset($fragmentNamesUsed[$fragmentName])) {
67
                $this->context->reportError(
68
                    new ValidationException(unusedFragmentMessage($fragmentName), [$fragmentDefinition])
0 ignored issues
show
It seems like $fragmentName can also be of type null; however, parameter $fragmentName of Digia\GraphQL\Validation\unusedFragmentMessage() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

68
                    new ValidationException(unusedFragmentMessage(/** @scrutinizer ignore-type */ $fragmentName), [$fragmentDefinition])
Loading history...
69
                );
70
            }
71
        }
72
73
        return new VisitorResult($node);
74
    }
75
}
76