InitMiddleware.php 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | likeshop100%开源免费商用商城系统
  4. // +----------------------------------------------------------------------
  5. // | 欢迎阅读学习系统程序代码,建议反馈是我们前进的动力
  6. // | 开源版本可自由商用,可去除界面版权logo
  7. // | 商业版本务必购买商业授权,以免引起法律纠纷
  8. // | 禁止对系统程序代码以任何目的,任何形式的再发布
  9. // | gitee下载:https://gitee.com/likeshop_gitee
  10. // | github下载:https://github.com/likeshop-github
  11. // | 访问官网:https://www.likeshop.cn
  12. // | 访问社区:https://home.likeshop.cn
  13. // | 访问手册:http://doc.likeshop.cn
  14. // | 微信公众号:likeshop技术社区
  15. // | likeshop团队 版权所有 拥有最终解释权
  16. // +----------------------------------------------------------------------
  17. // | author: likeshopTeam
  18. // +----------------------------------------------------------------------
  19. declare (strict_types=1);
  20. namespace app\businessapi\http\middleware;
  21. use app\businessapi\controller\BaseBusinesseController;
  22. use app\common\exception\ControllerExtendException;
  23. use app\common\service\JsonService;
  24. use think\exception\ClassNotFoundException;
  25. use think\exception\HttpException;
  26. class InitMiddleware
  27. {
  28. /**
  29. * @notes 初始化
  30. * @param $request
  31. * @param \Closure $next
  32. * @return mixed
  33. * @author 令狐冲
  34. * @date 2021/7/2 19:29
  35. */
  36. public function handle($request, \Closure $next)
  37. {
  38. //接口版本判断
  39. $version = $request->header('version');
  40. if (empty($version) && !$this->nocheck($request)) {
  41. return JsonService::fail('请求参数缺少接口版本号', [], 0, 0);
  42. }
  43. //获取控制器
  44. try {
  45. $controller = str_replace('.', '\\', $request->controller());
  46. $controller = '\\app\\businessapi\\controller\\' . $controller . 'Controller';
  47. $controllerClass = invoke($controller);
  48. if (($controllerClass instanceof BaseBusinesseController) === false) {
  49. throw new ControllerExtendException($controller, '404');
  50. }
  51. } catch (ClassNotFoundException $e) {
  52. throw new HttpException(404, 'controller not exists:' . $e->getClass());
  53. }
  54. //创建控制器对象
  55. $request->controllerObject = invoke($controller);
  56. return $next($request);
  57. }
  58. public function nocheck($request)
  59. {
  60. //特殊方法不验证版本号参数
  61. $noCheck = [
  62. ];
  63. $requestAction = $request->controller() . '/'. $request->action();
  64. return in_array($requestAction, $noCheck);
  65. }
  66. }