package org.dromara.payment.util;





import org.apache.commons.lang3.StringUtils;
import org.dromara.payment.exception.CustomException;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;

import java.util.Set;

public class ValidatorUtils {
    private static Validator validator =  Validation.buildDefaultValidatorFactory().getValidator();

    public static void validateEntity(Object object, Class<?>... groups) throws CustomException {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        if (!constraintViolations.isEmpty()) {
            StringBuilder msg = new StringBuilder();
            for (ConstraintViolation<Object> constraint : constraintViolations)
                msg.append("；").append(constraint.getMessage());
            throw new CustomException(msg.substring(1));
        }
    }

    public static String validateEntityNotError(Object object, Class<?>... groups) throws CustomException {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        StringBuilder msg = new StringBuilder();
        if (!constraintViolations.isEmpty()) {
            msg = new StringBuilder();
            for (ConstraintViolation<Object> constraint : constraintViolations)
                msg.append("；").append(constraint.getMessage());
        }
        return StringUtils.isNotBlank(msg) ? String.valueOf(msg.substring(1)) : "";
    }
}
