From 10893388c7755e7d43d7ff35753fedadc2849588 Mon Sep 17 00:00:00 2001 From: yoyosource Date: Wed, 17 Aug 2022 18:11:34 +0200 Subject: [PATCH] Update AbstractValidator --- .../steamwar/command/AbstractValidator.java | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/src/de/steamwar/command/AbstractValidator.java b/src/de/steamwar/command/AbstractValidator.java index 60efd19..4614681 100644 --- a/src/de/steamwar/command/AbstractValidator.java +++ b/src/de/steamwar/command/AbstractValidator.java @@ -19,6 +19,12 @@ package de.steamwar.command; +import lombok.AllArgsConstructor; +import lombok.RequiredArgsConstructor; + +import java.security.Provider; +import java.util.function.*; + @FunctionalInterface public interface AbstractValidator { @@ -32,8 +38,52 @@ public interface AbstractValidator { */ boolean validate(K sender, T value, MessageSender messageSender); + default Validator validate(C value, MessageSender messageSender) { + return new Validator<>(value, messageSender); + } + + @RequiredArgsConstructor + class Validator { + private final C value; + private final MessageSender messageSender; + + private boolean valid = true; + + public Validator map(Function mapper) { + return new Validator<>(mapper.apply(value), messageSender).and(ignore -> valid); + } + + public Validator and(Predicate predicate) { + valid &= predicate.test(value); + return this; + } + + public Validator or(Predicate predicate) { + valid |= predicate.test(value); + return this; + } + + public Validator 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); + } } }