digiaonline /
graphql-php
| 1 | <?php |
||
| 2 | |||
| 3 | namespace Digia\GraphQL\Validation\Rule; |
||
| 4 | |||
| 5 | use Digia\GraphQL\Language\Node\FragmentDefinitionNode; |
||
| 6 | use Digia\GraphQL\Language\Node\NameNode; |
||
| 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\duplicateFragmentMessage; |
||
| 11 | |||
| 12 | /** |
||
| 13 | * Unique fragment names |
||
| 14 | * |
||
| 15 | * A GraphQL document is only valid if all defined fragments have unique names. |
||
| 16 | */ |
||
| 17 | class UniqueFragmentNamesRule extends AbstractRule |
||
| 18 | { |
||
| 19 | /** |
||
| 20 | * @var NameNode[] |
||
| 21 | */ |
||
| 22 | protected $knownFragmentNames = []; |
||
| 23 | |||
| 24 | /** |
||
| 25 | * @inheritdoc |
||
| 26 | */ |
||
| 27 | protected function enterOperationDefinition(OperationDefinitionNode $node): VisitorResult |
||
| 28 | { |
||
| 29 | return new VisitorResult(null); // Fragments cannot be defined inside operation definitions. |
||
| 30 | } |
||
| 31 | |||
| 32 | /** |
||
| 33 | * @inheritdoc |
||
| 34 | */ |
||
| 35 | protected function enterFragmentDefinition(FragmentDefinitionNode $node): VisitorResult |
||
| 36 | { |
||
| 37 | $fragmentName = $node->getNameValue(); |
||
| 38 | |||
| 39 | if (isset($this->knownFragmentNames[$fragmentName])) { |
||
| 40 | $this->context->reportError( |
||
| 41 | new ValidationException( |
||
| 42 | duplicateFragmentMessage($fragmentName), |
||
|
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||
| 43 | [$this->knownFragmentNames[$fragmentName], $node->getName()] |
||
| 44 | ) |
||
| 45 | ); |
||
| 46 | } else { |
||
| 47 | $this->knownFragmentNames[$fragmentName] = $node->getName(); |
||
| 48 | } |
||
| 49 | |||
| 50 | return new VisitorResult(null); |
||
| 51 | } |
||
| 52 | } |
||
| 53 |