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

96 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;
2021-02-23 17:30:10 +08:00
use ReflectionException;
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
{
2021-04-19 14:38:17 +08:00
/** @var Closure|array */
protected array|Closure $handler;
protected mixed $request;
/**
* @param $handler
* @param $request
* @return static
* @throws NotFindClassException
* @throws ReflectionException
*/
public static function create($handler, $request): static
{
$class = new static();
$class->handler = $handler;
$class->request = $request;
if ($handler instanceof Closure) {
$class->bind();
}
$class->bindParam();
return $class;
}
/**
* @return mixed
* 执行函数
* @throws \Exception
*/
public function dispatch(): mixed
{
return \aop($this->handler, $this->request);
}
/**
* @throws ReflectionException
* @throws NotFindClassException
*/
protected function bind()
{
$class = $this->bindRequest(Snowflake::createObject(Controller::class));
$this->handler = Closure::bind($this->handler, $class);
}
/**
* @param $controller
* @return mixed
*/
protected function bindRequest($controller): mixed
{
$controller->request = Context::getContext('request');
$controller->headers = $controller->request?->headers;
$controller->input = $controller->request?->params;
return $controller;
}
/**
* 参数绑定
*/
protected function bindParam()
{
if ($this->handler instanceof Closure) {
return;
}
$controller = $this->handler[0];
$this->bindRequest($controller);
}
2020-08-31 01:27:08 +08:00
}