1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950 |
- <?php
- namespace App\Imports;
- use App\Http\Controllers\JsonResponseHelper;
- use Illuminate\Support\Collection;
- use Illuminate\Support\Facades\Validator;
- trait ImportValidatorHelper
- {
- use JsonResponseHelper;
- /**
- * @param Collection $collection
- * @param array $rules
- * @param array $messages
- * @param \Closure|null $additional 补充验证
- * @return void
- * @throws \App\Exceptions\ValidationException
- */
- protected function validatorByCollection(Collection $collection, array $rules, array $messages = [], \Closure $additional = null)
- {
- $errors = [];
- foreach ($collection as $index => $item) {
- $validator = Validator::make($item->toArray(), $rules, $messages);
- if ($validator->fails()) {
- $errors[$index + 1] = [
- 'index' => $index + 1,
- 'errors' => $validator->errors()->all()
- ];
- }
- if ($additional) {
- $error = call_user_func($additional, $item);
- if ($error) {
- $errors[$index + 1] = [
- 'index' => $index + 1,
- 'errors' => $error
- ];
- }
- }
- }
- if ($errors) {
- throw new \App\Exceptions\ValidationException(errors: array_values($errors));
- }
- }
- }
|