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

graphql.util.TreeTransformer Maven / Gradle / Ivy

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


import graphql.PublicApi;

import java.util.Collections;
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, Collections.emptyMap());
    }

    public T transform(T root, TraverserVisitor traverserVisitor, Map, Object> rootVars) {
        assertNotNull(root);

        NodeMultiZipper astMultiZipper = new NodeMultiZipper<>(root, Collections.emptyList(), nodeAdapter);

        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);
            }
        };

        Traverser traverser = Traverser.depthFirstWithNamedChildren(nodeAdapter::getNamedChildren, null, astMultiZipper);
        traverser.rootVars(rootVars);

        NodeMultiZipper multiZipperResult = (NodeMultiZipper) traverser.traverse(root, nodeTraverserVisitor).getAccumulatedResult();
        return multiZipperResult.toRootNode();
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy