<?php
/**
 *  ╔═══════════════════════════════════════════════════╗
 *  ║                                                   ║
 *  ║     ██╗  ██╗   █████╗    ██████╗                  ║
 *  ║     ██║  ██║  ██╔══██╗  ██╔═══██╗                 ║
 *  ║     ███████║  ███████║  ██║   ██║                 ║
 *  ║     ██╔══██║  ██╔══██║  ██║   ██║                 ║
 *  ║     ██║  ██║  ██║  ██║  ╚██████╔╝   SNS           ║
 *  ║                                                   ║    
 *  ║                                                   ║    
 *  ║     © 2023 HaoSNS™ All Rights Reserved            ║
 *  ║     官方网站: https://www.haosns.com                *
 *  ║     本代码由赣州乐易网络科技有限公司®提供             *
 *  ║                                                    *
 *  ║   未经授权禁止复制、传播或用于其他商业目的            *
 *  ║                                                   ║
 *  ╚═══════════════════════════════════════════════════╝
 */

declare (strict_types=1);

namespace app\api\http\middleware;


use app\common\exception\ControllerExtendException;
use app\common\service\JsonService;
use app\api\controller\BaseShopController;
use think\exception\ClassNotFoundException;
use think\exception\HttpException;

class InitMiddleware
{
    /**
     * @notes 初始化
     * @param $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, \Closure $next)
    {
        //接口版本判断
        // $version = $request->header('version');

        // if (empty($version) && !$this->nocheck($request)) {
        //     // 指定show为0，前端不弹出此报错
        //     return JsonService::fail('请求参数缺少接口版本号', [], 0, 0);
        // }

        //获取控制器
        try {
            $controller = str_replace('.', '\\', $request->controller());
            $controller = '\\app\\api\\controller\\' . $controller;
            $controllerClass = invoke($controller);
            if (($controllerClass instanceof BaseShopController) === false) {
                throw new ControllerExtendException($controller, '404');
            }
        } catch (ClassNotFoundException $e) {
            throw new HttpException(404, 'controller not exists:' . $e->getClass());
        }
        //创建控制器对象
        $request->controllerObject = invoke($controller);

        return $next($request);
    }


    /**
     * @notes 是否验证版本号
     * @param $request
     * @return bool
     */
    public function nocheck($request)
    {
        //特殊方法不验证版本号参数
        $noCheck = [
            'Pay/notifyMnp',
            'Pay/notifyOa',
            'Pay/notifyApp',
            'Pay/aliNotify'
        ];
        $requestAction = $request->controller() . '/'. $request->action();
        return in_array($requestAction, $noCheck);
    }

}