Files
kiri-core/HttpServer/Route/Dispatch/Dispatch.php
T

97 lines
1.7 KiB
PHP
Raw Normal View History

2020-08-31 01:27:08 +08:00
<?php
2020-10-29 18:17:25 +08:00
declare(strict_types=1);
2020-08-31 01:27:08 +08:00
namespace HttpServer\Route\Dispatch;
2020-10-29 18:17:25 +08:00
use Closure;
2020-08-31 01:27:08 +08:00
use HttpServer\Controller;
2020-08-31 10:38:24 +08:00
use HttpServer\Http\Context;
2020-10-29 18:17:25 +08:00
use HttpServer\Http\Request;
2021-02-23 17:30:10 +08:00
use ReflectionException;
2021-02-23 17:19:46 +08:00
use Snowflake\Exception\ComponentException;
2021-02-23 17:30:10 +08:00
use Snowflake\Exception\NotFindClassException;
2020-08-31 10:38:24 +08:00
use Snowflake\Snowflake;
2020-08-31 01:27:08 +08:00
/**
* Class Dispatch
* @package HttpServer\Route\Dispatch
*/
class Dispatch
{
2020-10-29 18:17:25 +08:00
/** @var Closure|array */
2020-12-15 17:31:34 +08:00
protected array|Closure $handler;
2020-08-31 01:27:08 +08:00
2020-12-15 17:36:24 +08:00
protected mixed $request;
2020-08-31 01:27:08 +08:00
2021-02-23 17:43:13 +08:00
2020-08-31 01:27:08 +08:00
/**
* @param $handler
* @param $request
* @return static
2021-02-23 17:43:13 +08:00
* @throws NotFindClassException
* @throws ReflectionException
2020-08-31 01:27:08 +08:00
*/
2020-12-15 17:31:34 +08:00
public static function create($handler, $request): static
2020-08-31 01:27:08 +08:00
{
2021-02-23 17:43:13 +08:00
$class = new static();
2020-08-31 01:27:08 +08:00
$class->handler = $handler;
$class->request = $request;
2020-10-29 18:17:25 +08:00
if ($handler instanceof Closure) {
2020-08-31 01:27:08 +08:00
$class->bind();
}
$class->bindParam();
return $class;
}
/**
* @return mixed
* 执行函数
*/
2020-12-15 17:35:51 +08:00
public function dispatch(): mixed
2020-08-31 01:27:08 +08:00
{
2020-12-15 17:35:51 +08:00
return call_user_func($this->handler, ...$this->request);
2020-08-31 01:27:08 +08:00
}
/**
2021-02-23 17:30:10 +08:00
* @throws ReflectionException
* @throws NotFindClassException
2020-08-31 01:27:08 +08:00
*/
protected function bind()
{
2021-02-23 17:30:10 +08:00
$class = $this->bindRequest(Snowflake::createObject(Controller::class));
2020-10-29 18:17:25 +08:00
$this->handler = Closure::bind($this->handler, $class);
2020-09-02 14:26:57 +08:00
}
/**
* @param $controller
* @return mixed
*/
2020-12-15 17:20:51 +08:00
protected function bindRequest($controller): mixed
2020-09-02 14:26:57 +08:00
{
$controller->request = Context::getContext('request');
2020-12-15 17:20:51 +08:00
$controller->headers = $controller->request?->headers;
$controller->input = $controller->request?->params;
2020-09-02 14:26:57 +08:00
return $controller;
2020-08-31 01:27:08 +08:00
}
/**
* 参数绑定
*/
protected function bindParam()
{
2020-10-29 18:17:25 +08:00
if ($this->handler instanceof Closure) {
2020-08-31 22:33:50 +08:00
return;
2020-08-31 01:27:08 +08:00
}
2020-08-31 22:33:50 +08:00
$controller = $this->handler[0];
2020-09-02 14:26:57 +08:00
$this->bindRequest($controller);
2020-08-31 01:27:08 +08:00
}
}