digiaonline /
graphql-php
| 1 | <?php |
||
| 2 | |||
| 3 | namespace Digia\GraphQL\Validation\Rule; |
||
| 4 | |||
| 5 | use Digia\GraphQL\Language\Node\NameNode; |
||
| 6 | use Digia\GraphQL\Language\Node\ObjectFieldNode; |
||
| 7 | use Digia\GraphQL\Language\Node\ObjectValueNode; |
||
| 8 | use Digia\GraphQL\Language\Visitor\VisitorResult; |
||
| 9 | use Digia\GraphQL\Validation\ValidationException; |
||
| 10 | use function Digia\GraphQL\Validation\duplicateInputFieldMessage; |
||
| 11 | |||
| 12 | /** |
||
| 13 | * Unique input field names |
||
| 14 | * |
||
| 15 | * A GraphQL input object value is only valid if all supplied fields are |
||
| 16 | * uniquely named. |
||
| 17 | */ |
||
| 18 | class UniqueInputFieldNamesRule extends AbstractRule |
||
| 19 | { |
||
| 20 | /** |
||
| 21 | * @var array[] |
||
| 22 | */ |
||
| 23 | protected $knownInputNamesStack = []; |
||
| 24 | |||
| 25 | /** |
||
| 26 | * @var NameNode[] |
||
| 27 | */ |
||
| 28 | protected $knownInputNames = []; |
||
| 29 | |||
| 30 | /** |
||
| 31 | * @inheritdoc |
||
| 32 | */ |
||
| 33 | protected function enterObjectValue(ObjectValueNode $node): VisitorResult |
||
| 34 | { |
||
| 35 | $this->knownInputNamesStack[] = $this->knownInputNames; |
||
| 36 | $this->knownInputNames = []; |
||
| 37 | |||
| 38 | return new VisitorResult($node); |
||
| 39 | } |
||
| 40 | |||
| 41 | /** |
||
| 42 | * @inheritdoc |
||
| 43 | */ |
||
| 44 | protected function enterObjectField(ObjectFieldNode $node): VisitorResult |
||
| 45 | { |
||
| 46 | $fieldName = $node->getNameValue(); |
||
| 47 | |||
| 48 | if (isset($this->knownInputNames[$fieldName])) { |
||
| 49 | $this->context->reportError( |
||
| 50 | new ValidationException( |
||
| 51 | duplicateInputFieldMessage($fieldName), |
||
|
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||
| 52 | [$this->knownInputNames[$fieldName], $node->getName()] |
||
| 53 | ) |
||
| 54 | ); |
||
| 55 | } else { |
||
| 56 | $this->knownInputNames[$fieldName] = $node->getName(); |
||
| 57 | } |
||
| 58 | |||
| 59 | return new VisitorResult($node); |
||
| 60 | } |
||
| 61 | |||
| 62 | /** |
||
| 63 | * @inheritdoc |
||
| 64 | */ |
||
| 65 | protected function leaveObjectValue(ObjectValueNode $node): VisitorResult |
||
| 66 | { |
||
| 67 | $this->knownInputNames = \array_pop($this->knownInputNamesStack); |
||
| 68 | |||
| 69 | return new VisitorResult($node); |
||
| 70 | } |
||
| 71 | } |
||
| 72 |