graphql.util.TreeTransformer Maven / Gradle / Ivy
package graphql.util;
import graphql.PublicApi;
import graphql.collect.ImmutableKit;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import static graphql.Assert.assertNotNull;
@PublicApi
public class TreeTransformer {
private final NodeAdapter nodeAdapter;
public TreeTransformer(NodeAdapter nodeAdapter) {
this.nodeAdapter = nodeAdapter;
}
public T transform(T root, TraverserVisitor traverserVisitor) {
return transform(root, traverserVisitor, ImmutableKit.emptyMap());
}
public T transform(T root, TraverserVisitor traverserVisitor, Map, Object> rootVars) {
assertNotNull(root);
TraverserVisitor nodeTraverserVisitor = new TraverserVisitor() {
@Override
public TraversalControl enter(TraverserContext context) {
NodeZipper nodeZipper = new NodeZipper<>(context.thisNode(), context.getBreadcrumbs(), nodeAdapter);
context.setVar(NodeZipper.class, nodeZipper);
context.setVar(NodeAdapter.class, nodeAdapter);
return traverserVisitor.enter(context);
}
@Override
public TraversalControl leave(TraverserContext context) {
return traverserVisitor.leave(context);
}
@Override
public TraversalControl backRef(TraverserContext context) {
return traverserVisitor.backRef(context);
}
};
List> zippers = new LinkedList<>();
Traverser traverser = Traverser.depthFirstWithNamedChildren(nodeAdapter::getNamedChildren, zippers, null);
traverser.rootVars(rootVars);
traverser.traverse(root, nodeTraverserVisitor);
NodeMultiZipper multiZipper = NodeMultiZipper.newNodeMultiZipperTrusted(root, zippers, nodeAdapter);
return multiZipper.toRootNode();
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy