ImportValidatorHelper.php 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. <?php
  2. namespace App\Imports;
  3. use App\Http\Controllers\JsonResponseHelper;
  4. use Illuminate\Support\Collection;
  5. use Illuminate\Support\Facades\Validator;
  6. trait ImportValidatorHelper
  7. {
  8. use JsonResponseHelper;
  9. /**
  10. * @param Collection $collection
  11. * @param array $rules
  12. * @param array $messages
  13. * @param \Closure|null $additional 补充验证
  14. * @return void
  15. * @throws \App\Exceptions\ValidationException
  16. */
  17. protected function validatorByCollection(Collection $collection, array $rules, array $messages = [], \Closure $additional = null)
  18. {
  19. $errors = [];
  20. foreach ($collection as $index => $item) {
  21. $validator = Validator::make($item->toArray(), $rules, $messages);
  22. if ($validator->fails()) {
  23. $errors[$index + 1] = [
  24. 'index' => $index + 1,
  25. 'errors' => $validator->errors()->all()
  26. ];
  27. }
  28. if ($additional) {
  29. $error = call_user_func($additional, $item);
  30. if ($error) {
  31. $errors[$index + 1] = [
  32. 'index' => $index + 1,
  33. 'errors' => $error
  34. ];
  35. }
  36. }
  37. }
  38. if ($errors) {
  39. throw new \App\Exceptions\ValidationException(errors: array_values($errors));
  40. }
  41. }
  42. }