graphql.validation.rules.NoUnusedFragments Maven / Gradle / Ivy
package graphql.validation.rules;
import graphql.Internal;
import graphql.language.Document;
import graphql.language.FragmentDefinition;
import graphql.language.FragmentSpread;
import graphql.language.OperationDefinition;
import graphql.validation.AbstractRule;
import graphql.validation.ValidationContext;
import graphql.validation.ValidationErrorCollector;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static graphql.validation.ValidationErrorType.UnusedFragment;
@Internal
public class NoUnusedFragments extends AbstractRule {
private final List allDeclaredFragments = new ArrayList<>();
private List usedFragments = new ArrayList<>();
private final Map> spreadsInDefinition = new LinkedHashMap<>();
private final List> fragmentsUsedDirectlyInOperation = new ArrayList<>();
public NoUnusedFragments(ValidationContext validationContext, ValidationErrorCollector validationErrorCollector) {
super(validationContext, validationErrorCollector);
}
@Override
public void checkOperationDefinition(OperationDefinition operationDefinition) {
usedFragments = new ArrayList<>();
fragmentsUsedDirectlyInOperation.add(usedFragments);
}
@Override
public void checkFragmentSpread(FragmentSpread fragmentSpread) {
usedFragments.add(fragmentSpread.getName());
}
@Override
public void checkFragmentDefinition(FragmentDefinition fragmentDefinition) {
allDeclaredFragments.add(fragmentDefinition);
usedFragments = new ArrayList<>();
spreadsInDefinition.put(fragmentDefinition.getName(), usedFragments);
}
@Override
public void documentFinished(Document document) {
List allUsedFragments = new ArrayList<>();
for (List fragmentsInOneOperation : fragmentsUsedDirectlyInOperation) {
for (String fragment : fragmentsInOneOperation) {
collectUsedFragmentsInDefinition(allUsedFragments, fragment);
}
}
for (FragmentDefinition fragmentDefinition : allDeclaredFragments) {
if (!allUsedFragments.contains(fragmentDefinition.getName())) {
String message = i18n(UnusedFragment, "NoUnusedFragments.unusedFragments", fragmentDefinition.getName());
addError(UnusedFragment, fragmentDefinition.getSourceLocation(), message);
}
}
}
private void collectUsedFragmentsInDefinition(List result, String fragmentName) {
if (result.contains(fragmentName)) return;
result.add(fragmentName);
List spreadList = spreadsInDefinition.get(fragmentName);
if (spreadList == null) {
return;
}
for (String fragment : spreadList) {
collectUsedFragmentsInDefinition(result, fragment);
}
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy