This commit is contained in:
2021-09-10 11:35:23 +08:00
parent 4753aee9c3
commit b497164f39
3 changed files with 256 additions and 261 deletions
+251 -250
View File
@@ -7,6 +7,7 @@ namespace Http\Route;
use Closure; use Closure;
use Exception; use Exception;
use Http\Context\Context;
use Http\Exception\RequestException; use Http\Exception\RequestException;
use JetBrains\PhpStorm\Pure; use JetBrains\PhpStorm\Pure;
use Kiri\Events\EventProvider; use Kiri\Events\EventProvider;
@@ -14,8 +15,8 @@ use Kiri\Exception\NotFindClassException;
use Kiri\Kiri; use Kiri\Kiri;
use ReflectionException; use ReflectionException;
use Server\Constant; use Server\Constant;
use Server\Events\OnAfterWorkerStart;
use Server\Constrict\RequestInterface; use Server\Constrict\RequestInterface;
use Server\Events\OnAfterWorkerStart;
/** /**
* Class Node * Class Node
@@ -24,291 +25,291 @@ use Server\Constrict\RequestInterface;
class Node class Node
{ {
public string $path = ''; public string $path = '';
public int $index = 0; public int $index = 0;
/** @var string[] */ /** @var string[] */
public array $method = []; public array $method = [];
/** @var Node[] $childes */ /** @var Node[] $childes */
public array $childes = []; public array $childes = [];
public array $group = []; public array $group = [];
private string $_error = ''; private string $_error = '';
private string $_dataType = ''; private string $_dataType = '';
/** @var array<string, array|Closure|null> */ /** @var array<string, array|Closure|null> */
private array $_handler = []; private array $_handler = [];
public string $htmlSuffix = '.html'; public string $htmlSuffix = '.html';
public bool $enableHtmlSuffix = false; public bool $enableHtmlSuffix = false;
/** @var array<string,mixed> */ /** @var array<string,mixed> */
public array $namespace = []; public array $namespace = [];
/** @var array<string,mixed> */ /** @var array<string,mixed> */
public array $middleware = []; public array $middleware = [];
public string $sourcePath = ''; public string $sourcePath = '';
/** @var array|Closure */ /** @var array|Closure */
public Closure|array $callback = []; public Closure|array $callback = [];
private string $_alias = ''; private string $_alias = '';
/** /**
* @param string $dataType * @param string $dataType
*/ */
public function setDataType(string $dataType) public function setDataType(string $dataType)
{ {
$this->_dataType = $dataType; $this->_dataType = $dataType;
} }
/** /**
* @throws NotFindClassException * @throws NotFindClassException
* @throws ReflectionException * @throws ReflectionException
*/ */
public function __construct(public Router $router) public function __construct(public Router $router)
{ {
$eventDispatcher = di(EventProvider::class); $eventDispatcher = di(EventProvider::class);
$eventDispatcher->on(OnAfterWorkerStart::class, [$this, 'setParameters']); $eventDispatcher->on(OnAfterWorkerStart::class, [$this, 'setParameters']);
} }
/** /**
* @param string $data * @param string $data
* @return mixed * @return mixed
*/ */
public function unpack(string $data): mixed public function unpack(string $data): mixed
{ {
if ($this->_dataType == 'json') { if ($this->_dataType == 'json') {
return json_decode($data, true); return json_decode($data, true);
} }
if ($this->_dataType == 'serializes') { if ($this->_dataType == 'serializes') {
return unserialize($data); return unserialize($data);
} }
return $data; return $data;
} }
/** /**
* @param string|array|Closure $handler * @param string|array|Closure $handler
* @param string $method * @param string $method
* @param string $path * @param string $path
* @return Node * @return Node
* @throws ReflectionException * @throws ReflectionException
*/ */
public function setHandler(string|array|Closure $handler, string $method, string $path): static public function setHandler(string|array|Closure $handler, string $method, string $path): static
{ {
$this->sourcePath = '/' . ltrim($path, '/'); $this->sourcePath = '/' . ltrim($path, '/');
if (is_string($handler) && str_contains($handler, '@')) { if (is_string($handler) && str_contains($handler, '@')) {
$handler = $this->splitHandler($handler); $handler = $this->splitHandler($handler);
} else if ($handler != null && !is_callable($handler, true)) { } else if ($handler != null && !is_callable($handler, true)) {
$this->_error = 'Controller is con\'t exec.'; $this->_error = 'Controller is con\'t exec.';
return $this; return $this;
} }
$this->_handler[$method] = [$handler, $this->resolveMethodParams($handler)]; $this->_handler[$method] = [$handler, $this->resolveMethodParams($handler)];
return $this; return $this;
} }
/** /**
* @param $dispatcher * @param $dispatcher
* @return array * @return array
* @throws \ReflectionException * @throws \ReflectionException
*/ */
private function resolveMethodParams($dispatcher): array private function resolveMethodParams($dispatcher): array
{ {
$container = Kiri::getDi(); $container = Kiri::getDi();
if ($dispatcher instanceof Closure) { if ($dispatcher instanceof Closure) {
$_injectParameters = $container->getFunctionParameters($dispatcher); $_injectParameters = $container->getFunctionParameters($dispatcher);
} else { } else {
$_injectParameters = $container->getMethodParameters( $_injectParameters = $container->getMethodParameters(
$dispatcher[0]::class, $dispatcher[1]); $dispatcher[0]::class, $dispatcher[1]);
} }
return $_injectParameters; return $_injectParameters;
} }
/** /**
* @param string $handler * @param string $handler
* @return array * @return array
*/ */
private function splitHandler(string $handler): array private function splitHandler(string $handler): array
{ {
list($controller, $action) = explode('@', $handler); list($controller, $action) = explode('@', $handler);
if (!class_exists($controller) && !empty($this->namespace)) { if (!class_exists($controller) && !empty($this->namespace)) {
$controller = implode('\\', $this->namespace) . '\\' . $controller; $controller = implode('\\', $this->namespace) . '\\' . $controller;
} }
return [Kiri::getDi()->get($controller), $action]; return [Kiri::getDi()->get($controller), $action];
} }
/** /**
* @param string $method * @param string $method
* @param $handler * @param $handler
* @param $_injectParameters * @param $_injectParameters
* @throws ReflectionException * @throws ReflectionException
* @throws Exception * @throws Exception
*/ */
private function injectMiddleware(string $method, $handler, $_injectParameters): void private function injectMiddleware(string $method, $handler, $_injectParameters): void
{ {
$callback = (new Pipeline())->overall($this->router->getMiddleware()) $callback = (new Pipeline())->overall($this->router->getMiddleware())
->through($this->middleware[$method] ?? []) ->through($this->middleware[$method] ?? [])
->through(MiddlewareManager::get($handler)) ->through(MiddlewareManager::get($handler))
->send($_injectParameters) ->send($_injectParameters)
->then($handler); ->then($handler);
HandlerProviders::add($method, $this->sourcePath, $callback); HandlerProviders::add($method, $this->sourcePath, $callback);
} }
/** /**
* @throws ReflectionException * @throws ReflectionException
*/ */
public function setParameters(): static public function setParameters(): static
{ {
if (empty($this->_handler)) { if (empty($this->_handler)) {
return $this; return $this;
} }
foreach ($this->_handler as $method => $dispatcher) { foreach ($this->_handler as $method => $dispatcher) {
$this->injectMiddleware($method, ...$dispatcher); $this->injectMiddleware($method, ...$dispatcher);
} }
$this->_handler = []; $this->_handler = [];
return $this; return $this;
} }
/** /**
* @return array * @return array
*/ */
#[Pure] protected function annotation(): array #[Pure] protected function annotation(): array
{ {
return $this->getMiddleWares(); return $this->getMiddleWares();
} }
/** /**
* @param RequestInterface $request * @param RequestInterface $request
* @return bool * @return bool
*/ */
#[Pure] public function methodAllow(RequestInterface $request): bool #[Pure] public function methodAllow(RequestInterface $request): bool
{ {
if (!in_array($request->getMethod(), $this->method)) { if (!in_array($request->getMethod(), $this->method)) {
return true; return true;
} }
return $this->method == 'any'; return $this->method == 'any';
} }
/** /**
* @return bool * @return bool
* @throws Exception * @throws Exception
*/ */
public function checkSuffix(): bool public function checkSuffix(): bool
{ {
if ($this->enableHtmlSuffix) { if ($this->enableHtmlSuffix) {
$url = request()->getUri()->getPath(); $url = request()->getUri()->getPath();
$nowLength = strlen($this->htmlSuffix); $nowLength = strlen($this->htmlSuffix);
if (strpos($url, $this->htmlSuffix) !== strlen($url) - $nowLength) { if (strpos($url, $this->htmlSuffix) !== strlen($url) - $nowLength) {
return false; return false;
} }
} }
return true; return true;
} }
/** /**
* @return string * @return string
* 错误信息 * 错误信息
*/ */
public function getError(): string public function getError(): string
{ {
return $this->_error; return $this->_error;
} }
/** /**
* @param Node $node * @param Node $node
* @return Node * @return Node
*/ */
public function addChild(Node $node): Node public function addChild(Node $node): Node
{ {
$this->childes[] = $node; $this->childes[] = $node;
return $node; return $node;
} }
/** /**
* @param string $search * @param string $search
* @return Node|null * @return Node|null
* @throws Exception * @throws Exception
*/ */
public function findNode(string $search): ?Node public function findNode(string $search): ?Node
{ {
if (empty($this->childes)) { if (empty($this->childes)) {
return null; return null;
} }
foreach ($this->childes as $val) { foreach ($this->childes as $val) {
if ($search == $val->path) { if ($search == $val->path) {
return $val; return $val;
} }
} }
return null; return null;
} }
/** /**
* @param string $alias * @param string $alias
* @return $this * @return $this
* 别称 * 别称
*/ */
public function alias(string $alias): static public function alias(string $alias): static
{ {
$this->_alias = $alias; $this->_alias = $alias;
return $this; return $this;
} }
/** /**
* @return string * @return string
*/ */
public function getAlias(): string public function getAlias(): string
{ {
return $this->_alias; return $this->_alias;
} }
/** /**
* @param $method * @param $method
* @param Closure|array $class * @param Closure|array $class
* @return $this * @return $this
*/ */
public function addMiddleware($method, Closure|array $class): static public function addMiddleware($method, Closure|array $class): static
{ {
if (empty($class)) return $this; if (empty($class)) return $this;
if (!isset($this->middleware[$method])) { if (!isset($this->middleware[$method])) {
$this->middleware[$method] = []; $this->middleware[$method] = [];
} }
foreach ($class as $closure) { foreach ($class as $closure) {
if (in_array($closure, $this->middleware[$method])) { if (in_array($closure, $this->middleware[$method])) {
continue; continue;
} }
$this->middleware[$method][] = $closure; $this->middleware[$method][] = $closure;
} }
return $this; return $this;
} }
/** /**
* @return array * @return array
*/ */
public function getMiddleWares(): array public function getMiddleWares(): array
{ {
return $this->middleware; return $this->middleware;
} }
/** /**
@@ -317,16 +318,16 @@ class Node
* @throws RequestException * @throws RequestException
* @throws Exception * @throws Exception
*/ */
public function dispatch(RequestInterface $request): mixed public function dispatch(RequestInterface $request): mixed
{ {
if (!in_array($request->getMethod(), $this->method)) { if (!in_array($request->getMethod(), $this->method)) {
throw new RequestException(Constant::STATUS_405_MESSAGE, 405); throw new RequestException(Constant::STATUS_405_MESSAGE, 405);
} }
$handlerProviders = HandlerProviders::get($this->sourcePath, $request->getMethod()); $handlerProviders = HandlerProviders::get($this->sourcePath, $request->getMethod());
if (empty($handlerProviders)) { if (empty($handlerProviders)) {
throw new RequestException(Constant::STATUS_404_MESSAGE, 404); throw new RequestException(Constant::STATUS_404_MESSAGE, 404);
} }
return $handlerProviders->interpreter($request); return $handlerProviders->interpreter($request);
} }
} }
+2 -2
View File
@@ -57,11 +57,11 @@ class Request implements RequestInterface
{ {
$serverRequest = ServerRequest::createServerRequest($request); $serverRequest = ServerRequest::createServerRequest($request);
Context::setContext(ResponseInterface::class, $response = new Response()); Context::setContext(ResponseInterface::class, new Response());
Context::setContext(RequestInterface::class, $serverRequest); Context::setContext(RequestInterface::class, $serverRequest);
return [Kiri::getDi()->get(Request::class), $response]; return Kiri::getDi()->get(Request::class);
} }
+3 -9
View File
@@ -8,7 +8,7 @@ use Http\Exception\RequestException;
use Http\Route\Node; use Http\Route\Node;
use Kiri\Core\Help; use Kiri\Core\Help;
use Server\Constant; use Server\Constant;
use Server\Constrict\RequestInterface; use Server\Constrict\Request as ScRequest;
use Server\Constrict\ResponseInterface; use Server\Constrict\ResponseInterface;
use Server\Events\OnAfterRequest; use Server\Events\OnAfterRequest;
use Server\SInterface\OnClose; use Server\SInterface\OnClose;
@@ -42,22 +42,16 @@ class Http extends \Server\Abstracts\Http implements OnClose, OnConnect
public function onRequest(Request $request, Response $response): void public function onRequest(Request $request, Response $response): void
{ {
try { try {
[$request, $psr7Response] = \Server\Constrict\Request::create($request); $node = $this->router->Branch_search($Psr7Request = ScRequest::create($request));
/** @var RequestInterface $request */
$node = $this->router->Branch_search($request);
if (!($node instanceof Node)) { if (!($node instanceof Node)) {
throw new RequestException(Constant::STATUS_404_MESSAGE, 404); throw new RequestException(Constant::STATUS_404_MESSAGE, 404);
} }
$psr7Response = $node->dispatch($request); if (!(($psr7Response = $node->dispatch($Psr7Request)) instanceof ResponseInterface)) {
if (!($psr7Response instanceof ResponseInterface)) {
$psr7Response = $this->transferToResponse($psr7Response); $psr7Response = $this->transferToResponse($psr7Response);
} }
} catch (Error | \Throwable $exception) { } catch (Error | \Throwable $exception) {
$psr7Response = $this->exceptionHandler->emit($exception, $this->response); $psr7Response = $this->exceptionHandler->emit($exception, $this->response);
} finally { } finally {
if (!isset($psr7Response)) {
return;
}
$this->responseEmitter->sender($response, $psr7Response); $this->responseEmitter->sender($response, $psr7Response);
$this->eventDispatch->dispatch(new OnAfterRequest()); $this->eventDispatch->dispatch(new OnAfterRequest());
} }