GQLInlineFragment.java

package net.morimekta.providence.graphql.gql;

import net.morimekta.providence.descriptor.PMessageDescriptor;
import net.morimekta.util.collect.UnmodifiableList;

import javax.annotation.Nonnull;
import javax.annotation.concurrent.Immutable;
import java.util.List;
import java.util.Objects;

/**
 * An inline fragment, defining type-conditional field
 * in-place.
 *
 * {@inheritDoc}
 */
@Immutable
public class GQLInlineFragment implements GQLFragment {
    private final PMessageDescriptor<?> descriptor;
    private final List<GQLSelection>    selectionSet;

    /**
     * Inline fragment with field set.
     *
     * @param descriptor Descriptor of type defined in this fragment.
     * @param selectionSet Field selectionSet for the fragment.
     */
    public GQLInlineFragment(@Nonnull PMessageDescriptor<?> descriptor,
                             @Nonnull List<GQLSelection> selectionSet) {
        this.descriptor = descriptor;
        this.selectionSet = UnmodifiableList.copyOf(selectionSet);
    }

    @Nonnull
    @Override
    public PMessageDescriptor<?> getTypeCondition() {
        return descriptor;
    }

    @Nonnull
    @Override
    public List<GQLSelection> getSelectionSet() {
        return selectionSet;
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("... on ")
               .append(descriptor.getName())
               .append(" {");

        boolean first = true;
        for (GQLSelection entry : selectionSet) {
            if (first) {
                first = false;
            } else {
                builder.append(", ");
            }
            builder.append(entry.toString());
        }
        builder.append("}");
        return builder.toString();
    }

    @Override
    public int hashCode() {
        return Objects.hash(getClass(),
                            descriptor,
                            selectionSet);
    }

    @Override
    public boolean equals(Object o) {
        if (o == this) return true;
        if (!(o instanceof GQLInlineFragment)) return false;
        GQLInlineFragment other = (GQLInlineFragment) o;
        return Objects.equals(descriptor, other.descriptor) &&
               Objects.equals(selectionSet, other.selectionSet);
    }
}