BaseDto.php 1.12 KB
Newer Older
zazaname's avatar
zazaname committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
<?php

namespace App\Http\Dto;

use App\Exceptions\ValidateException;
use App\Utils\Response;
use Illuminate\Support\Facades\Validator;

class BaseDto
{
    protected $rules   = [];

    protected $message = [];

    public $requestData;

    protected $validator;

    /**
     * 数据校验
     *
     * @param array $data
     * @throws ValidateException
     */
    public function dataValidate(array $data)
    {
        //基础校验器取数据方法
        $this->validator = Validator::make($data, $this->rules, $this->message);

        $this->requestData = $this->validator->getData();

        if ($this->validator->fails()) {
            throw new ValidateException($this->validator->errors()->first());
        }

        $this->validator->after(function () {
            $bool = $this->customValidate();
            if (!$bool) {
                throw new ValidateException($this->validator->errors()->first(),Response::PARAM_ERROR);
            }
        });
    }

    /**
     * 自定义验证(如有需要,子类进行重写)
     */
    protected function customValidate(): bool
    {
        return true;
    }

}