Dispatcher.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006~2018 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. namespace think\http\middleware;
  12. use think\Request;
  13. use think\Response;
  14. class Dispatcher implements DispatcherInterface
  15. {
  16. protected $queue;
  17. public function __construct($middlewares = [])
  18. {
  19. $this->queue = (array) $middlewares;
  20. }
  21. /**
  22. * {@inheritdoc}
  23. */
  24. public function add($middleware)
  25. {
  26. $this->assertValid($middleware);
  27. $this->queue[] = $middleware;
  28. }
  29. /**
  30. * {@inheritdoc}
  31. */
  32. public function insert($middleware)
  33. {
  34. $this->assertValid($middleware);
  35. array_unshift($this->queue, $middleware);
  36. }
  37. /**
  38. * {@inheritdoc}
  39. */
  40. public function all()
  41. {
  42. return $this->queue;
  43. }
  44. /**
  45. * {@inheritdoc}
  46. */
  47. public function dispatch(Request $request)
  48. {
  49. $requestHandler = $this->resolve();
  50. return call_user_func($requestHandler, $request);
  51. }
  52. protected function resolve()
  53. {
  54. return function (Request $request) {
  55. $middleware = array_shift($this->queue);
  56. if (null !== $middleware) {
  57. $response = call_user_func($middleware, $request, $this->resolve());
  58. if (!$response instanceof Response) {
  59. throw new \LogicException('The middleware must return Response instance');
  60. }
  61. return $response;
  62. } else {
  63. throw new MissingResponseException('The queue was exhausted, with no response returned');
  64. }
  65. };
  66. }
  67. protected function assertValid($middleware)
  68. {
  69. if (!is_callable($middleware)) {
  70. throw new \InvalidArgumentException('The middleware is invalid');
  71. }
  72. }
  73. }