Middleware.php 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006~2021 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: Slince <taosikai@yeah.net>
  10. // +----------------------------------------------------------------------
  11. declare (strict_types = 1);
  12. namespace think;
  13. use Closure;
  14. use InvalidArgumentException;
  15. use LogicException;
  16. use think\exception\Handle;
  17. use Throwable;
  18. /**
  19. * 中间件管理类
  20. * @package think
  21. */
  22. class Middleware
  23. {
  24. /**
  25. * 中间件执行队列
  26. * @var array
  27. */
  28. protected $queue = [];
  29. /**
  30. * 应用对象
  31. * @var App
  32. */
  33. protected $app;
  34. public function __construct(App $app)
  35. {
  36. $this->app = $app;
  37. }
  38. /**
  39. * 导入中间件
  40. * @access public
  41. * @param array $middlewares
  42. * @param string $type 中间件类型
  43. * @return void
  44. */
  45. public function import(array $middlewares = [], string $type = 'global'): void
  46. {
  47. foreach ($middlewares as $middleware) {
  48. $this->add($middleware, $type);
  49. }
  50. }
  51. /**
  52. * 注册中间件
  53. * @access public
  54. * @param mixed $middleware
  55. * @param string $type 中间件类型
  56. * @return void
  57. */
  58. public function add($middleware, string $type = 'global'): void
  59. {
  60. $middleware = $this->buildMiddleware($middleware, $type);
  61. if (!empty($middleware)) {
  62. $this->queue[$type][] = $middleware;
  63. $this->queue[$type] = array_unique($this->queue[$type], SORT_REGULAR);
  64. }
  65. }
  66. /**
  67. * 注册路由中间件
  68. * @access public
  69. * @param mixed $middleware
  70. * @return void
  71. */
  72. public function route($middleware): void
  73. {
  74. $this->add($middleware, 'route');
  75. }
  76. /**
  77. * 注册控制器中间件
  78. * @access public
  79. * @param mixed $middleware
  80. * @return void
  81. */
  82. public function controller($middleware): void
  83. {
  84. $this->add($middleware, 'controller');
  85. }
  86. /**
  87. * 注册中间件到开始位置
  88. * @access public
  89. * @param mixed $middleware
  90. * @param string $type 中间件类型
  91. */
  92. public function unshift($middleware, string $type = 'global')
  93. {
  94. $middleware = $this->buildMiddleware($middleware, $type);
  95. if (!empty($middleware)) {
  96. if (!isset($this->queue[$type])) {
  97. $this->queue[$type] = [];
  98. }
  99. array_unshift($this->queue[$type], $middleware);
  100. }
  101. }
  102. /**
  103. * 获取注册的中间件
  104. * @access public
  105. * @param string $type 中间件类型
  106. * @return array
  107. */
  108. public function all(string $type = 'global'): array
  109. {
  110. return $this->queue[$type] ?? [];
  111. }
  112. /**
  113. * 调度管道
  114. * @access public
  115. * @param string $type 中间件类型
  116. * @return Pipeline
  117. */
  118. public function pipeline(string $type = 'global')
  119. {
  120. return (new Pipeline())
  121. ->through(array_map(function ($middleware) {
  122. return function ($request, $next) use ($middleware) {
  123. [$call, $params] = $middleware;
  124. if (is_array($call) && is_string($call[0])) {
  125. $call = [$this->app->make($call[0]), $call[1]];
  126. }
  127. $response = call_user_func($call, $request, $next, ...$params);
  128. if (!$response instanceof Response) {
  129. throw new LogicException('The middleware must return Response instance');
  130. }
  131. return $response;
  132. };
  133. }, $this->sortMiddleware($this->queue[$type] ?? [])))
  134. ->whenException([$this, 'handleException']);
  135. }
  136. /**
  137. * 结束调度
  138. * @param Response $response
  139. */
  140. public function end(Response $response)
  141. {
  142. foreach ($this->queue as $queue) {
  143. foreach ($queue as $middleware) {
  144. [$call] = $middleware;
  145. if (is_array($call) && is_string($call[0])) {
  146. $instance = $this->app->make($call[0]);
  147. if (method_exists($instance, 'end')) {
  148. $instance->end($response);
  149. }
  150. }
  151. }
  152. }
  153. }
  154. /**
  155. * 异常处理
  156. * @param Request $passable
  157. * @param Throwable $e
  158. * @return Response
  159. */
  160. public function handleException($passable, Throwable $e)
  161. {
  162. /** @var Handle $handler */
  163. $handler = $this->app->make(Handle::class);
  164. $handler->report($e);
  165. return $handler->render($passable, $e);
  166. }
  167. /**
  168. * 解析中间件
  169. * @access protected
  170. * @param mixed $middleware
  171. * @param string $type 中间件类型
  172. * @return array
  173. */
  174. protected function buildMiddleware($middleware, string $type): array
  175. {
  176. if (is_array($middleware)) {
  177. [$middleware, $params] = $middleware;
  178. }
  179. if ($middleware instanceof Closure) {
  180. return [$middleware, $params ?? []];
  181. }
  182. if (!is_string($middleware)) {
  183. throw new InvalidArgumentException('The middleware is invalid');
  184. }
  185. //中间件别名检查
  186. $alias = $this->app->config->get('middleware.alias', []);
  187. if (isset($alias[$middleware])) {
  188. $middleware = $alias[$middleware];
  189. }
  190. if (is_array($middleware)) {
  191. $this->import($middleware, $type);
  192. return [];
  193. }
  194. return [[$middleware, 'handle'], $params ?? []];
  195. }
  196. /**
  197. * 中间件排序
  198. * @param array $middlewares
  199. * @return array
  200. */
  201. protected function sortMiddleware(array $middlewares)
  202. {
  203. $priority = $this->app->config->get('middleware.priority', []);
  204. uasort($middlewares, function ($a, $b) use ($priority) {
  205. $aPriority = $this->getMiddlewarePriority($priority, $a);
  206. $bPriority = $this->getMiddlewarePriority($priority, $b);
  207. return $bPriority - $aPriority;
  208. });
  209. return $middlewares;
  210. }
  211. /**
  212. * 获取中间件优先级
  213. * @param $priority
  214. * @param $middleware
  215. * @return int
  216. */
  217. protected function getMiddlewarePriority($priority, $middleware)
  218. {
  219. [$call] = $middleware;
  220. if (is_array($call) && is_string($call[0])) {
  221. $index = array_search($call[0], array_reverse($priority));
  222. return false === $index ? -1 : $index;
  223. }
  224. return -1;
  225. }
  226. }