<?php

declare (strict_types=1);

namespace app\common\middleware;

/**
 * Description of Permission
 * 访问权限中间件
 * @author sgq
 */
class Permission {

    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next) {
        $controller = $request->controller();
        $ref = new \ReflectionClass("\app\admin\controller\\" . $controller);
        $action = $request->action();
        $comment = $ref->getMethod($action)->getDocComment();
        $old_auth_url = "";
        if ($comment) {
            if (preg_match("/(?<=@auth {{).*?(?=}})/", $comment, $result)) {
                //成功提取@auth {{}}出中间内容则需要判断权限
                $old_auth_url = strtolower($result[0]);
                //对比权限
            }
        }
        $module = strtolower(app("http")->getName());
        $controller = strtolower($request->controller());
        $action = strtolower($request->action());
        $url = sprintf("/%s/%s/%s", $module, $controller, $action);
        if (!\app\common\api\MenuApi::chkPermission($url, $old_auth_url))
            return json(["code" => 403, "msg" => "没有权限"])->code(403);
        return $next($request);
    }

}
