1. 修复 isEmpty 的 bug。

2. 重构校验器。
This commit is contained in:
zhouxy108 2022-12-09 17:37:10 +08:00
parent 70f4a9fb45
commit 08f8da3516
8 changed files with 374 additions and 154 deletions

View File

@ -2,14 +2,18 @@ package xyz.zhouxy.plusone.validator;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import xyz.zhouxy.plusone.exception.InvalidInputException;
/**
* 校验器
*
* <p>可以使用以下方式初始化一个校验器</p>
* <p>
* 可以使用以下方式初始化一个校验器
* </p>
*
* <pre>
* BaseValidator&lt;Integer&gt; validator = new BaseValidator&lt;&gt;() {
@ -20,7 +24,9 @@ import xyz.zhouxy.plusone.exception.InvalidInputException;
* };
* </pre>
*
* <p>也可以通过继承本类定义一个校验器可使用单例模式</p>
* <p>
* 也可以通过继承本类定义一个校验器可使用单例模式
* </p>
*
* <p>
* 然后通过校验器的 {@link #validate} 方法
@ -43,30 +49,40 @@ import xyz.zhouxy.plusone.exception.InvalidInputException;
*/
public abstract class BaseValidator<T> {
private final List<RuleInfo<T>> rules = new ArrayList<>();
private final List<RuleInfo<T, ?>> rules = new ArrayList<>();
protected BaseValidator() {
}
protected final void ruleFor(Predicate<T> rule, String errorMessage) {
this.rules.add(new RuleInfo<>(rule, errorMessage));
protected final void withRule(Predicate<T> rule, String errorMessage) {
withRule(rule, () -> new InvalidInputException(errorMessage));
}
protected final <E extends RuntimeException> void withRule(Predicate<T> rule, Supplier<E> exceptionCreator) {
withRule(rule, value -> exceptionCreator.get());
}
protected final <E extends RuntimeException> void withRule(Predicate<T> rule, Function<T, E> exceptionCreator) {
this.rules.add(new RuleInfo<>(rule, exceptionCreator));
}
public void validate(T obj) {
this.rules.forEach((RuleInfo<T> ruleInfo) -> {
if (!ruleInfo.rule.test(obj)) {
throw new InvalidInputException(ruleInfo.message);
}
});
this.rules.forEach(ruleInfo -> ruleInfo.validate(obj));
}
protected static class RuleInfo<T> {
Predicate<T> rule;
String message;
protected static class RuleInfo<T, E extends RuntimeException> {
private final Predicate<T> rule;
private final Function<T, E> exceptionCreator;
public RuleInfo(Predicate<T> rule, String message) {
private RuleInfo(Predicate<T> rule, Function<T, E> exceptionCreator) {
this.rule = rule;
this.message = message;
this.exceptionCreator = exceptionCreator;
}
private void validate(T obj) {
if (!rule.test(obj)) {
throw exceptionCreator.apply(obj);
}
}
}
}

View File

@ -1,129 +0,0 @@
package xyz.zhouxy.plusone.validator;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
import java.util.function.Predicate;
import cn.hutool.core.exceptions.ValidateException;
import lombok.AllArgsConstructor;
import xyz.zhouxy.plusone.constant.RegexConsts;
import xyz.zhouxy.plusone.util.RegexUtil;
public abstract class BaseValidator2<T> {
private List<ValidValueHolder<T, ?>> hs = new ArrayList<>();
protected final <R> ValidValueHolder<T, R> ruleFor(Function<T, R> getter) {
ValidValueHolder<T, R> validValueHolder = new ValidValueHolder<>(getter);
hs.add(validValueHolder);
return validValueHolder;
}
public void validate(T obj) {
for (var holder : hs) {
var value = holder.getter.apply(obj);
for (var rule : holder.rules) {
if (!rule.condition.test(value)) {
throw new ValidateException(rule.errMsg);
}
}
}
}
}
class ValidValueHolder<T, R> {
Function<T, R> getter;
List<RuleInfo<Object>> rules = new ArrayList<>();
public ValidValueHolder(Function<T, R> getter) {
this.getter = getter;
}
private void addRule(Predicate<Object> condition, String errMsg) {
this.rules.add(new RuleInfo<>(condition, errMsg));
}
public ValidValueHolder<T, R> nonNull(String errMsg) {
addRule(Objects::nonNull, errMsg);
return this;
}
public ValidValueHolder<T, R> nonEmpty(String errMsg) {
addRule(value -> {
if (value == null) {
return false;
}
if (value instanceof Collection) {
return ((Collection<?>) value).isEmpty();
}
if (value instanceof String) {
return ((String) value).isEmpty();
}
return false;
}, errMsg);
return this;
}
public ValidValueHolder<T, R> size(int min, int max, String errMsg) {
addRule(value -> {
if (value == null) {
return false;
}
if (value instanceof Collection) {
int size = ((Collection<?>) value).size();
return size >= min && size <= max;
}
return true;
}, errMsg);
return this;
}
public ValidValueHolder<T, R> length(int min, int max, String errMsg) {
addRule(value -> {
if (value == null) {
return false;
}
if (value instanceof String) {
int length = ((String) value).length();
return length >= min && length <= max;
}
return true;
}, errMsg);
return this;
}
public ValidValueHolder<T, R> matches(String regex, String errMsg) {
addRule(input -> RegexUtil.matches(regex, (String) input), errMsg);
return this;
}
public ValidValueHolder<T, R> matchesOr(String[] regexs, String errMsg) {
addRule(input -> RegexUtil.matchesOr((String) input, regexs), errMsg);
return this;
}
public ValidValueHolder<T, R> matchesAnd(String[] regexs, String errMsg) {
addRule(input -> RegexUtil.matchesAnd((String) input, regexs), errMsg);
return this;
}
public ValidValueHolder<T, R> email(String errMsg) {
return matches(RegexConsts.EMAIL, errMsg);
}
@SuppressWarnings("unchecked")
public ValidValueHolder<T, R> and(Predicate<R> condition, String errMsg) {
addRule((Predicate<Object>) condition, errMsg);
return this;
}
@AllArgsConstructor
static final class RuleInfo<R> {
Predicate<R> condition;
String errMsg;
}
}

View File

@ -36,7 +36,7 @@ import java.util.function.Predicate;
*/
public final class Validator<T> extends BaseValidator<T> {
public final Validator<T> addRule(final Predicate<T> rule, final String errorMessage) {
ruleFor(rule, errorMessage);
withRule(rule, errorMessage);
return this;
}
}

View File

@ -0,0 +1,21 @@
package xyz.zhouxy.plusone.validator.validator2;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
public abstract class BaseValidator2<T> {
private List<ValueValidator<T, ?>> hs = new ArrayList<>();
protected final <R> ValueValidator<T, R> ruleFor(Function<T, R> getter) {
ValueValidator<T, R> validValueHolder = new ValueValidator<>(getter);
hs.add(validValueHolder);
return validValueHolder;
}
public void validate(T obj) {
this.hs.forEach(valueValidator -> valueValidator.validateProperty(obj));
}
}

View File

@ -0,0 +1,310 @@
package xyz.zhouxy.plusone.validator.validator2;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import xyz.zhouxy.plusone.constant.RegexConsts;
import xyz.zhouxy.plusone.exception.InvalidInputException;
import xyz.zhouxy.plusone.util.RegexUtil;
public class ValueValidator<DTO, PROPERTY> {
Function<DTO, PROPERTY> getter;
List<RuleInfo<PROPERTY, ?>> rules = new ArrayList<>();
public ValueValidator(Function<DTO, PROPERTY> getter) {
this.getter = getter;
}
private void withRule(Predicate<PROPERTY> condition, String errMsg) {
withRule(condition, value -> new InvalidInputException(errMsg));
}
private <E extends RuntimeException> void withRule(Predicate<PROPERTY> condition,
Function<PROPERTY, E> exceptionCreator) {
this.rules.add(new RuleInfo<>(condition, exceptionCreator));
}
// ====================
// ====== Object ======
// ====================
// ====== notNull =====
public ValueValidator<DTO, PROPERTY> notNull(String errMsg) {
return notNull(value -> new InvalidInputException(errMsg));
}
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> notNull(Supplier<E> exceptionCreator) {
return notNull(value -> exceptionCreator.get());
}
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> notNull(Function<PROPERTY, E> exceptionCreator) {
withRule(Objects::nonNull, exceptionCreator);
return this;
}
// ====== isNull =====
public ValueValidator<DTO, PROPERTY> isNull(String errMsg) {
return isNull(value -> new InvalidInputException(errMsg));
}
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> isNull(Supplier<E> exceptionCreator) {
return isNull(value -> exceptionCreator.get());
}
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> isNull(Function<PROPERTY, E> exceptionCreator) {
withRule(Objects::isNull, exceptionCreator);
return this;
}
// ===== equals =====
public ValueValidator<DTO, PROPERTY> equalsThat(Object that) {
return equalsThat(that, value -> new InvalidInputException(String.format("(%s) 必须与 (%s) 相等", value, that)));
}
public ValueValidator<DTO, PROPERTY> equalsThat(Object that, String errMsg) {
return equalsThat(that, value -> new InvalidInputException(errMsg));
}
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> equalsThat(
Object that, Supplier<E> exceptionCreator) {
return equalsThat(that, value -> exceptionCreator.get());
}
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> equalsThat(
Object that, Function<PROPERTY, E> exceptionCreator) {
withRule(value -> Objects.equals(value, that), exceptionCreator);
return this;
}
// ===== state =====
public ValueValidator<DTO, PROPERTY> state(Predicate<PROPERTY> condition) {
return state(condition, value -> new InvalidInputException("无效的用户输入"));
}
public ValueValidator<DTO, PROPERTY> state(Predicate<PROPERTY> condition, String errMsg) {
return state(condition, value -> new InvalidInputException(errMsg));
}
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> state(
Predicate<PROPERTY> condition,
Supplier<E> exceptionCreator) {
return state(condition, value -> exceptionCreator.get());
}
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> state(
Predicate<PROPERTY> condition,
Function<PROPERTY, E> exceptionCreator) {
withRule(condition, exceptionCreator);
return this;
}
// =================
// ====== int ======
// =================
public ValueValidator<DTO, PROPERTY> between(int min, int max) {
return between(min, max, String.format("数值不在 %d 和 %d 之间", min, max));
}
public ValueValidator<DTO, PROPERTY> between(int min, int max, String errMsg) {
return between(min, max, value -> new InvalidInputException(errMsg));
}
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> between(int min, int max,
Supplier<E> exceptionCreator) {
return between(min, max, value -> exceptionCreator.get());
}
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> between(int min, int max,
Function<PROPERTY, E> exceptionCreator) {
withRule(value -> ((int) value >= min && (int) value < max), exceptionCreator);
return this;
}
// ================================
// ====== Collection, String ======
// ================================
// ====== notEmpty =====
public ValueValidator<DTO, PROPERTY> notEmpty(String errMsg) {
return notEmpty(value -> new InvalidInputException(errMsg));
}
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> notEmpty(Supplier<E> exceptionCreator) {
return notEmpty(value -> exceptionCreator.get());
}
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> notEmpty(Function<PROPERTY, E> exceptionCreator) {
withRule(value -> {
if (value == null) {
return false;
}
if (value instanceof Collection) {
return !((Collection<?>) value).isEmpty();
}
if (value instanceof String) {
return !((String) value).isEmpty();
}
return false;
}, exceptionCreator);
return this;
}
// ====== isEmpty =====
public ValueValidator<DTO, PROPERTY> isEmpty(String errMsg) {
return isEmpty(value -> new InvalidInputException(errMsg));
}
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> isEmpty(Supplier<E> exceptionCreator) {
return isEmpty(value -> exceptionCreator.get());
}
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> isEmpty(Function<PROPERTY, E> exceptionCreator) {
withRule(value -> {
if (value == null) {
return false;
}
if (value instanceof Collection) {
return ((Collection<?>) value).isEmpty();
}
if (value instanceof String) {
return ((String) value).isEmpty();
}
return false;
}, exceptionCreator);
return this;
}
// =====================
// ====== boolean ======
// =====================
// ====== isTrue ======
public ValueValidator<DTO, PROPERTY> isTrue() {
return isTrue(value -> new InvalidInputException("Value must be true."));
}
public ValueValidator<DTO, PROPERTY> isTrue(String errMsg) {
return isTrue(value -> new InvalidInputException(errMsg));
}
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> isTrue(Supplier<E> exceptionCreator) {
return isTrue(value -> exceptionCreator.get());
}
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> isTrue(Function<PROPERTY, E> exceptionCreator) {
withRule(Boolean.TRUE::equals, exceptionCreator);
return this;
}
// ====== isFalse ======
public ValueValidator<DTO, PROPERTY> isFalse() {
return isFalse(value -> new InvalidInputException("Value must be true."));
}
public ValueValidator<DTO, PROPERTY> isFalse(String errMsg) {
return isFalse(value -> new InvalidInputException(errMsg));
}
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> isFalse(Supplier<E> exceptionCreator) {
return isFalse(value -> exceptionCreator.get());
}
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> isFalse(Function<PROPERTY, E> exceptionCreator) {
withRule(Boolean.FALSE::equals, exceptionCreator);
return this;
}
// ====================
// ====== String ======
// ====================
// ===== matches =====
public ValueValidator<DTO, PROPERTY> matches(String regex, String errMsg) {
return matches(regex, value -> new InvalidInputException(errMsg));
}
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> matches(String regex,
Supplier<E> exceptionCreator) {
return matches(regex, value -> exceptionCreator.get());
}
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> matches(String regex,
Function<PROPERTY, E> exceptionCreator) {
withRule(input -> RegexUtil.matches((String) input, regex), exceptionCreator);
return this;
}
// ===== matchesOr =====
public ValueValidator<DTO, PROPERTY> matchesOr(String[] regexs, String errMsg) {
return matchesOr(regexs, value -> new InvalidInputException(errMsg));
}
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> matchesOr(String[] regexs,
Supplier<E> exceptionCreator) {
return matchesOr(regexs, value -> exceptionCreator.get());
}
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> matchesOr(String[] regexs,
Function<PROPERTY, E> exceptionCreator) {
withRule(input -> RegexUtil.matchesOr((String) input, regexs), exceptionCreator);
return this;
}
// ===== matchesOr =====
public ValueValidator<DTO, PROPERTY> matchesAnd(String[] regexs, String errMsg) {
withRule(input -> RegexUtil.matchesAnd((String) input, regexs), errMsg);
return this;
}
// ===== email =====
public ValueValidator<DTO, PROPERTY> email(String errMsg) {
return email(value -> new InvalidInputException(errMsg));
}
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> email(Supplier<E> exceptionCreator) {
return email(value -> exceptionCreator.get());
}
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> email(Function<PROPERTY, E> exceptionCreator) {
return matches(RegexConsts.EMAIL, exceptionCreator);
}
// ========================================================================
void validateProperty(DTO obj) {
PROPERTY value = this.getter.apply(obj);
this.rules.forEach(rule -> rule.validate(value));
}
@AllArgsConstructor(access = AccessLevel.PRIVATE)
private static final class RuleInfo<V, E extends RuntimeException> {
private final Predicate<V> condition;
private final Function<V, E> exceptionCreator;
private void validate(V obj) {
if (!this.condition.test(obj)) {
throw exceptionCreator.apply(obj);
}
}
}
}

View File

@ -1,4 +1,4 @@
package xyz.zhouxy.plusone.validator;
package xyz.zhouxy.plusone.validatortest;
import org.junit.jupiter.api.Test;
@ -6,12 +6,13 @@ import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import xyz.zhouxy.plusone.constant.RegexConsts;
import xyz.zhouxy.plusone.validator.validator2.BaseValidator2;
class BaseValidator2Test {
@Test
void testValid() {
LoginCommand loginCommand = new LoginCommand("13169053215@qq.com", "8GouTDE53a", false);
LoginCommand loginCommand = new LoginCommand("13169053215@qq.com", "A1qZ6c-cQ78=^(", false);
LoginCommandValidator.INSTANCE.validate(loginCommand);
System.err.println(loginCommand);
}
@ -32,10 +33,11 @@ class LoginCommandValidator extends BaseValidator2<LoginCommand> {
private LoginCommandValidator() {
ruleFor(loginCommand -> loginCommand.getAccount())
.nonNull("邮箱地址不能为空")
.matchesOr(new String[] { RegexConsts.EMAIL, RegexConsts.MOBILE_PHONE }, "请输入邮箱地址或手机号");
.notNull("邮箱地址不能为空")
.matchesOr(new String[] { RegexConsts.EMAIL, RegexConsts.MOBILE_PHONE }, value -> new RuntimeException('"' + value + "\" 不是邮箱地址或手机号"));
ruleFor(loginCommand -> loginCommand.getPwd())
.nonNull("密码不能为空")
.notNull("密码不能为空")
.notEmpty("密码不能为空")
.matches(RegexConsts.PASSWORD, "密码格式错误");
}
}

View File

@ -15,13 +15,13 @@ import xyz.zhouxy.plusone.validator.DtoValidator;
@DtoValidator(LoginByOtpCommand.class)
public class LoginByOtpCommandValidator extends BaseValidator<LoginByOtpCommand> {
public LoginByOtpCommandValidator() {
ruleFor(loginCommand -> {
withRule(loginCommand -> {
String principal = loginCommand.getPrincipal();
return StringUtils.hasText(principal)
&&
RegexUtil.matchesOr(principal, RegexConsts.EMAIL, RegexConsts.MOBILE_PHONE);
}, "输入邮箱地址或手机号");
ruleFor(loginCommand -> {
withRule(loginCommand -> {
String otp = loginCommand.getOtp();
return StringUtils.hasText(otp) && Pattern.matches(RegexConsts.CAPTCHA, otp);
}, "验证码不符合要求");

View File

@ -15,13 +15,13 @@ import xyz.zhouxy.plusone.validator.DtoValidator;
@DtoValidator(LoginByPasswordCommand.class)
public class LoginByPasswordCommandValidator extends BaseValidator<LoginByPasswordCommand> {
public LoginByPasswordCommandValidator() {
ruleFor(loginCommand -> {
withRule(loginCommand -> {
String principal = loginCommand.getPrincipal();
return StringUtils.hasText(principal)
&&
RegexUtil.matchesOr(principal, RegexConsts.USERNAME, RegexConsts.EMAIL, RegexConsts.MOBILE_PHONE, principal);
}, "输入用户名、邮箱地址或手机号");
ruleFor(loginCommand -> {
withRule(loginCommand -> {
String password = loginCommand.getPassword();
return StringUtils.hasText(password)
&&