From c4290b3a431c19d916f72663f9989e4306e4dbda Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=90=91=E6=9E=97?= Date: Wed, 19 Apr 2023 13:20:12 +0800 Subject: [PATCH] =?UTF-8?q?=E5=8F=98=E6=9B=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Handler.php | 32 +++++++++++++++++++++++++++----- 1 file changed, 27 insertions(+), 5 deletions(-) diff --git a/src/Handler.php b/src/Handler.php index 6b5ab48..2d360df 100644 --- a/src/Handler.php +++ b/src/Handler.php @@ -3,6 +3,9 @@ declare(strict_types=1); namespace Kiri\Router; +use Closure; +use Kiri\Di\Context; +use Psr\Http\Message\RequestInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\RequestHandlerInterface; @@ -13,11 +16,18 @@ class Handler implements RequestHandlerInterface /** - * @param array|\Closure $handler - * @param array $parameter + * @var RequestInterface|mixed|null */ - public function __construct(public array|\Closure $handler, public array $parameter) + private RequestInterface $request; + + /** + * @param array|Closure $handler + * @param array $parameter + * @throws + */ + public function __construct(public array|Closure $handler, public array $parameter) { + $this->request = \Kiri::service()->get('request'); } @@ -26,7 +36,7 @@ class Handler implements RequestHandlerInterface */ public function isClosure(): bool { - return $this->handler instanceof \Closure; + return $this->handler instanceof Closure; } @@ -62,7 +72,19 @@ class Handler implements RequestHandlerInterface public function handle(ServerRequestInterface $request): ResponseInterface { // TODO: Implement handle() method. - return call_user_func($this->handler, ...$this->parameter); + if ($this->handler instanceof Closure) { + return call_user_func($this->handler, ...$this->parameter); + } + [$controller, $action] = $this->handler; + if ($controller->beforeAction($this->request)) { + $response = call_user_func($this->handler, ...$this->parameter); + $controller->afterAction($response); + } else { + /** @var Response $response */ + $response = \Kiri::service()->get('response'); + $response->withStatus(500,'BeforeAction error'); + } + return $response; } }