package sk.emm.portal.validation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Component;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ValidationUtils;
import javax.annotation.Nonnull;
import java.util.Objects;
@Component
public class UpdateIdValidator {
private final Logger log = LoggerFactory.getLogger(UpdateIdValidator.class);
public static final String ID = "id";
public void validate(Object dto, @Nonnull Long urlId, JpaRepository<?,Long> repository) throws BindException {
BindingResult errors = new BeanPropertyBindingResult(dto, dto.getClass().getSimpleName());
ValidationUtils.rejectIfEmpty(errors, ID, "id.not.null");
if (!Objects.equals(urlId, errors.getFieldValue(ID))) {
errors.rejectValue(ID, "id.invalid");
}
if (!repository.existsById(urlId)) {
errors.rejectValue(ID, "id.not.found");
}
if (errors.hasErrors()) {
log.error("...update id validation errors: {}", errors);
throw new BindException(errors);
}
}
}