<?php
// +----------------------------------------------------------------------
// | 麦沃德科技赋能开发者，助力中小企业发展 
// +----------------------------------------------------------------------
// | Copyright (c) 2017～2024  www.wdadmin.cn    All rights reserved.
// +----------------------------------------------------------------------
// | Wdadmin系统产品软件并不是自由软件，不加密，并不代表开源，未经许可不可自由转售和商用
// +----------------------------------------------------------------------
// | Author: MY WORLD Team <bd@maiwd.cn>   www.wdadmin.cn
// +----------------------------------------------------------------------
namespace app\adminapi\middleware;

use core\base\BaseAdminController;
use think\exception\HttpException;

class AdminInit
{
    public function handle($request, \Closure $next)
    {
        try {
            $pathinfo = $request->pathinfo();
            // 处理pathinfo，去除操作方法名
            $path = explode('/', $pathinfo);
            if (count($path) > 1) {
                array_pop($path);
            }
            $controllerStr = implode('\\', $path);
            $controllerStr = str_replace('.', '\\', $controllerStr);

            // 处理控制器类名首字母大写
            $parts = explode('\\', $controllerStr);
            if (!empty($parts)) {
                $lastKey = count($parts) - 1;
                $parts[$lastKey] = ucfirst($parts[$lastKey]);
                $controllerStr = implode('\\', $parts);
            }

            $controller = '\\app\\adminapi\\controller\\' . $controllerStr . 'Controller';

            $controllerClass = app()->make($controller);
            if ($controllerStr !== 'Swagger' && ($controllerClass instanceof BaseAdminController) === false) {
                throw new HttpException(404,'控制器没有继承基础类');
            }
        } catch (\think\exception\ClassNotFoundException $e) {
            throw new HttpException(404, $e->getClass().'不存在');
        }

        $request->controllerObject = invoke($controller);

        return $next($request);
    }

}