/* (C) 2022 YiRing, Inc. */
package com.yiring.common.validation;

import com.yiring.common.util.Commons;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import jakarta.validation.Validation;
import jakarta.validation.ValidatorFactory;
import java.util.Set;
import lombok.Cleanup;
import lombok.experimental.UtilityClass;

/**
 * 校验工具类
 *
 * @author Jim
 * @version 0.1
 * 2022/10/24 17:11
 */

@SuppressWarnings("unused")
@UtilityClass
public class ValidateUtil {

    /**
     * 对象校验
     *
     * @param t      目标对象
     * @param groups 分组
     * @param <T>    目标类
     * @throws ConstraintViolationException 校验异常（结合全局异常拦截，快速失败模式）
     */
    public static <T> void validate(T t, Class<?>... groups) {
        @Cleanup
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Set<ConstraintViolation<T>> constraintViolations = factory.getValidator().validate(t, groups);
        if (Commons.isNotEmpty(constraintViolations)) {
            throw new ConstraintViolationException(constraintViolations);
        }
    }
}
