package com.ruoyi.common.validRule.allowSize;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.List;
import java.util.Objects;

/**
 * 2023/10/20
 * 枚举值校验
 */
public class AllowSizeValidator implements ConstraintValidator<AllowSize, List> {

	private AllowSize annotation;

	@Override
	public void initialize(AllowSize constraintAnnotation) {
		this.annotation = constraintAnnotation;
	}

	/**
	 * 判断是否校验成功
	 * @param value 待校验的值
	 * @return 校验结果
	 */
	@Override
	public boolean isValid(List value, ConstraintValidatorContext context) {
		// 如果待校验的值为null，是否校验通过
		if (value == null) {
			return annotation.allowNull();
		}
		try {
			int size = value.size();
			if (annotation.filterNull()) {
				size = (int) value.stream().filter(Objects::nonNull).count();
			}
			for (int s : annotation.sizes()) {
				if (s == size) {
					return true;
				}
			}
			return false;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}

