Skip to content

Commit

Permalink
add CollectionValue#onClear, CollectionValue#onClearValue
Browse files Browse the repository at this point in the history
  • Loading branch information
Maru32768 committed Jan 13, 2022
1 parent ccc0daa commit 70e7996
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
25 changes: 25 additions & 0 deletions src/main/java/net/kunmc/lab/configlib/command/CollectionValue.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,13 @@
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;

public abstract class CollectionValue<T extends Collection<E>, E> extends Value<T> {
private final transient List<BiFunction<T, CommandContext, Boolean>> addListeners = new ArrayList<>();
private final transient List<BiFunction<T, CommandContext, Boolean>> removeListeners = new ArrayList<>();
private final transient List<Function<CommandContext, Boolean>> clearListeners = new ArrayList<>();

public CollectionValue(T value) {
super(value);
Expand Down Expand Up @@ -94,5 +97,27 @@ protected boolean onRemoveValue(T newValue, CommandContext ctx) {

protected abstract boolean clearableByCommand();


public <U extends CollectionValue<T, E>> U onClear(Consumer<CommandContext> listener) {
return onClear(ctx -> {
listener.accept(ctx);
return false;
});
}

/**
* @return true if you want to cancel event, otherwise false
*/
public <U extends CollectionValue<T, E>> U onClear(Function<CommandContext, Boolean> listener) {
clearListeners.add(listener);
return ((U) this);
}

protected boolean onClearValue(CommandContext ctx) {
return clearListeners.stream()
.map(x -> x.apply(ctx))
.reduce(false, (a, b) -> a || b);
}

protected abstract String clearMessage(String entryName);
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ public ModifyClearCommand(Field field, CollectionValue value, BaseConfig config)

@Override
public void execute(CommandContext ctx) {
if (configValue.onClearValue(ctx)) {
return;
}

((Collection) configValue.value()).clear();
ctx.success(configValue.clearMessage(field.getName()));

Expand Down

0 comments on commit 70e7996

Please sign in to comment.