All Downloads are FREE. Search and download functionalities are using the official Maven repository.

graphql.validation.rules.NoUnusedVariables Maven / Gradle / Ivy

There is a newer version: 230521-nf-execution
Show newest version
package graphql.validation.rules;


import graphql.Internal;
import graphql.language.OperationDefinition;
import graphql.language.VariableDefinition;
import graphql.language.VariableReference;
import graphql.validation.AbstractRule;
import graphql.validation.ValidationContext;
import graphql.validation.ValidationErrorCollector;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import static graphql.validation.ValidationErrorType.UnusedVariable;

@Internal
public class NoUnusedVariables extends AbstractRule {

    private final List variableDefinitions = new ArrayList<>();
    private final Set usedVariables = new LinkedHashSet<>();

    public NoUnusedVariables(ValidationContext validationContext, ValidationErrorCollector validationErrorCollector) {
        super(validationContext, validationErrorCollector);
        setVisitFragmentSpreads(true);
    }

    @Override
    public void leaveOperationDefinition(OperationDefinition operationDefinition) {
        for (VariableDefinition variableDefinition : variableDefinitions) {
            if (!usedVariables.contains(variableDefinition.getName())) {
                String message = i18n(UnusedVariable, "NoUnusedVariables.unusedVariable", variableDefinition.getName());
                addError(UnusedVariable, variableDefinition.getSourceLocation(), message);
            }
        }
    }

    @Override
    public void checkOperationDefinition(OperationDefinition operationDefinition) {
        usedVariables.clear();
        variableDefinitions.clear();
    }

    @Override
    public void checkVariableDefinition(VariableDefinition variableDefinition) {
        variableDefinitions.add(variableDefinition);
    }

    @Override
    public void checkVariable(VariableReference variableReference) {
        usedVariables.add(variableReference.getName());
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy