<?php
declare (strict_types = 1);

namespace app\middleware;

use think\facade\Validate;

class CheckValidata
{

    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        $action = request()->action();  //根据路由获取对应的方法
        $controller = request()->controller();  //根据路由获取对应的方法
        $module =  app('http')->getName(); //获取模块名
        $param = $request->param(); //获取所有的参数
        $fun = $module . "_" . $controller."_".$action;//数组的key的验证规则

        $this->$fun($param);
        return $next($request);
    }

    function __call($name, $arguments)
    {
        $filename = dirname(dirname(dirname(__FILE__)))."/config/validata.php";
        if(file_exists($filename)) {
            require  $filename;
            if(isset($validatarule[$name])) {
                $validate = Validate::rule($validatarule[$name]);
                $this->returnMsg($validate, $arguments[0]);
            }
        }
    }

    public function returnMsg($validate, $param)
    {
        $result = $validate->check($param);
        if (!$result) {
            $msg = $validate->getError();
            $rs['code'] = "000001";
            $rs['message'] = $msg;
            $rs['data'] = [];
            echo json_encode($rs);
            exit;
        }
    }


}
