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

90 lines
1.4 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;
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-10-30 01:29:29 +08:00
protected $handler;
2020-08-31 01:27:08 +08:00
2020-10-29 18:17:25 +08:00
protected Request $request;
2020-08-31 01:27:08 +08:00
/**
* @param $handler
* @param $request
* @return static
*/
public static function create($handler, $request)
{
$class = new static();
$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
* 执行函数
*/
public function dispatch()
{
return call_user_func($this->handler, $this->request);
}
/**
* 设置作用域
*/
protected function bind()
{
2020-09-02 14:26:57 +08:00
$class = $this->bindRequest(new Controller());
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
*/
protected function bindRequest($controller)
{
$controller->request = Context::getContext('request');
$controller->headers = $controller->request->headers;
$controller->input = $controller->request->params;
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
}
}