public function __invoke(ValidationContext $context) { $visitedFragmentNames = new \stdClass(); $variableDefs = []; $variableNameUsed = new \stdClass(); return ['visitSpreadFragments' => true, Node::OPERATION_DEFINITION => ['enter' => function () use(&$visitedFragmentNames, &$variableDefs, &$variableNameUsed) { $visitedFragmentNames = new \stdClass(); $variableDefs = []; $variableNameUsed = new \stdClass(); }, 'leave' => function () use(&$visitedFragmentNames, &$variableDefs, &$variableNameUsed) { $errors = []; foreach ($variableDefs as $def) { if (empty($variableNameUsed->{$def->variable->name->value})) { $errors[] = new Error(Messages::unusedVariableMessage($def->variable->name->value), [$def]); } } return !empty($errors) ? $errors : null; }], Node::VARIABLE_DEFINITION => function ($def) use(&$variableDefs) { $variableDefs[] = $def; return Visitor::skipNode(); }, Node::VARIABLE => function ($variable) use(&$variableNameUsed) { $variableNameUsed->{$variable->name->value} = true; }, Node::FRAGMENT_SPREAD => function ($spreadAST) use(&$visitedFragmentNames) { // Only visit fragments of a particular name once per operation if (!empty($visitedFragmentNames->{$spreadAST->name->value})) { return Visitor::skipNode(); } $visitedFragmentNames->{$spreadAST->name->value} = true; }]; }
private function unusedVar($varName, $line, $column) { return new FormattedError(Messages::unusedVariableMessage($varName), [new SourceLocation($line, $column)]); }