package com.jeequan.jeepay.core.service;

import com.jeequan.jeepay.core.exception.BizException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;

import javax.validation.ConstraintViolation;
import java.util.Set;

/**
 * TODO
 *
 * @author deng
 * @since 2024/5/9
 */
@Service
public class ValidatorService {

    @Autowired
    private LocalValidatorFactoryBean validatorFactoryBean;

    public <T> void validate(T subject, Class<?>... groupClass) {
        Set<ConstraintViolation<T>> validate = validatorFactoryBean.validate(subject, groupClass);
        if (!validate.isEmpty()) {
            StringBuilder validError = new StringBuilder();
            validate.forEach(item -> validError.append(item.getMessage()).append(","));
            throw new BizException(validError.subSequence(0, validError.length() - 1).toString());
        }
    }
}
