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

io.sphere.sdk.attributes.AttributeExtraction Maven / Gradle / Ivy

The newest version!
package io.sphere.sdk.attributes;

import io.sphere.sdk.models.Base;

import java.util.Optional;
import java.util.function.Function;

public final class AttributeExtraction extends Base {
    private final AttributeDefinition attributeDefinition;
    private final Attribute attribute;
    private final Optional value;

    public AttributeExtraction(final AttributeDefinition attributeDefinition, final Attribute attribute, final Optional value) {
        this.attributeDefinition = attributeDefinition;
        this.attribute = attribute;
        this.value = value;
    }

    public static  AttributeExtraction of(final AttributeDefinition attributeDefinition, final Attribute attribute) {
        return of(attributeDefinition, attribute, Optional.empty());
    }

    private static  AttributeExtraction of(final AttributeDefinition attributeDefinition, final Attribute attribute, final Optional value) {
        return new AttributeExtraction<>(attributeDefinition, attribute, value);
    }

    private AttributeExtraction withValue(final Optional value) {
        return of(attributeDefinition, attribute, value);
    }

    public  AttributeExtraction ifGuarded(final AttributeAccess extraction, final Function> function) {
        return value.map(x -> this).orElseGet(() -> {
            final Optional transformed = calculateValue(extraction).flatMap(value -> function.apply(value));
            return withValue(transformed);
        });
    }

    public  AttributeExtraction ifIs(final AttributeAccess extraction, final Function function) {
        return ifIs(extraction, function, x -> true);
    }

    private  Optional calculateValue(final AttributeAccess extraction) {
        Optional valueOption = Optional.empty();
        if (extraction.canHandle(attributeDefinition)) {
            final AttributeMapper mapper = extraction.attributeMapper();
            final I attributeValue = attribute.getValue(mapper);
            valueOption = Optional.of(attributeValue);
        }
        return valueOption;
    }

    public  AttributeExtraction ifIs(final AttributeAccess extraction, final Function function, final java.util.function.Predicate guard) {
        return value.map(x -> this).orElseGet(() -> {
            final Optional newValue = calculateValue(extraction).flatMap(attributeValue -> {
                Optional mappedValue = Optional.empty();
                if (guard.test(attributeValue)) {
                    mappedValue = Optional.of(function.apply(attributeValue));
                }
                return mappedValue;
            });
            return withValue(newValue);
        });
    }

    public Optional getValue() {
        return value;
    }
}