package com.ssyf.common.web.valid;

import cn.hutool.core.util.StrUtil;

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

/**
 * 数组元素校验类
 * @author huwei
 * @date 2023/9/25 22:02
 */
public class ArrayElementValidator implements ConstraintValidator<ArrayElement, List<String>> {

    /**
     * 约束对象
     */
    private ArrayElement arrayElement;

    @Override
    public void initialize(ArrayElement arrayElement) {
        this.arrayElement = arrayElement;
    }

    @Override
    public boolean isValid(List<String> list, ConstraintValidatorContext constraintValidatorContext) {
        if (list == null || list.isEmpty()) {
            return false;
        }
        //个数校验
        if(list.size() > arrayElement.size()){
            return false;
        }

        //元素格式校验
        if(StrUtil.isNotBlank(arrayElement.regexp())) {
            for (String ele : list) {
                if (!ele.matches(arrayElement.regexp())){
                    return false;
                }
            }
        }
        return true;
    }
}