Merge pull request 'Update AbstractValidator' (#14) from CMDAPIBetterValidationAPI into master
Alle Prüfungen waren erfolgreich
SteamWarCI Build successful
Alle Prüfungen waren erfolgreich
SteamWarCI Build successful
Reviewed-on: #14
Dieser Commit ist enthalten in:
Commit
6cb3bc5ff5
@ -19,6 +19,12 @@
|
||||
|
||||
package de.steamwar.command;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import java.util.function.BooleanSupplier;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
@FunctionalInterface
|
||||
public interface AbstractValidator<K, T> {
|
||||
|
||||
@ -32,8 +38,57 @@ public interface AbstractValidator<K, T> {
|
||||
*/
|
||||
boolean validate(K sender, T value, MessageSender messageSender);
|
||||
|
||||
default <C> Validator<C> validate(C value, MessageSender messageSender) {
|
||||
return new Validator<>(value, messageSender);
|
||||
}
|
||||
|
||||
@RequiredArgsConstructor
|
||||
class Validator<C> {
|
||||
private final C value;
|
||||
private final MessageSender messageSender;
|
||||
|
||||
private boolean valid = true;
|
||||
|
||||
public <M> Validator<M> map(Function<C, M> mapper) {
|
||||
return new Validator<>(mapper.apply(value), messageSender).set(valid);
|
||||
}
|
||||
|
||||
public Validator<C> set(boolean value) {
|
||||
this.valid = value;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Validator<C> and(Predicate<C> predicate) {
|
||||
valid &= predicate.test(value);
|
||||
return this;
|
||||
}
|
||||
|
||||
public Validator<C> or(Predicate<C> predicate) {
|
||||
valid |= predicate.test(value);
|
||||
return this;
|
||||
}
|
||||
|
||||
public Validator<C> errorMessage(String s, Object... args) {
|
||||
if (!valid) messageSender.send(s, args);
|
||||
return this;
|
||||
}
|
||||
|
||||
public boolean result() {
|
||||
return valid;
|
||||
}
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
interface MessageSender {
|
||||
void send(String s, Object... args);
|
||||
|
||||
default boolean send(boolean condition, String s, Object... args) {
|
||||
if (condition) send(s, args);
|
||||
return condition;
|
||||
}
|
||||
|
||||
default boolean send(BooleanSupplier condition, String s, Object... args) {
|
||||
return send(condition.getAsBoolean(), s, args);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Laden…
In neuem Issue referenzieren
Einen Benutzer sperren