AbstractRequestHandler.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace Hyperf\Dispatcher;
  12. use Hyperf\Dispatcher\Exceptions\InvalidArgumentException;
  13. use Psr\Container\ContainerInterface;
  14. use Psr\Http\Server\MiddlewareInterface;
  15. use function is_string;
  16. abstract class AbstractRequestHandler
  17. {
  18. protected int $offset = 0;
  19. /**
  20. * @param array $middlewares All middlewares to dispatch by dispatcher
  21. * @param MiddlewareInterface|object $coreHandler The core middleware of dispatcher
  22. */
  23. public function __construct(protected array $middlewares, protected $coreHandler, protected ContainerInterface $container)
  24. {
  25. $this->middlewares = array_values($this->middlewares);
  26. }
  27. protected function handleRequest($request)
  28. {
  29. if (! isset($this->middlewares[$this->offset])) {
  30. $handler = $this->coreHandler;
  31. } else {
  32. $handler = $this->middlewares[$this->offset];
  33. is_string($handler) && $handler = $this->container->get($handler);
  34. }
  35. if (! $handler || ! method_exists($handler, 'process')) {
  36. throw new InvalidArgumentException('Invalid middleware, it has to provide a process() method.');
  37. }
  38. return $handler->process($request, $this->next());
  39. }
  40. protected function next(): self
  41. {
  42. ++$this->offset;
  43. return $this;
  44. }
  45. }