This commit is contained in:
2021-04-26 12:32:38 +08:00
parent 9ae3dc8f8a
commit 0db6782135
3 changed files with 528 additions and 526 deletions
+72 -70
View File
@@ -9,6 +9,7 @@ use HttpServer\Abstracts\Callback;
use HttpServer\Exception\ExitException; use HttpServer\Exception\ExitException;
use HttpServer\Http\Request as HRequest; use HttpServer\Http\Request as HRequest;
use HttpServer\Http\Response as HResponse; use HttpServer\Http\Response as HResponse;
use HttpServer\Route\Router;
use Snowflake\Error\Logger; use Snowflake\Error\Logger;
use Snowflake\Event; use Snowflake\Event;
use Snowflake\Snowflake; use Snowflake\Snowflake;
@@ -24,87 +25,88 @@ class OnRequest extends Callback
{ {
public Event $event; public Event $event;
public Logger $logger; public Logger $logger;
/** public Router $router;
* @throws Exception
*/
public function init()
{
$this->event = Snowflake::app()->getEvent();
}
/** /**
* @param Request $request * @throws Exception
* @param Response $response */
* @return void public function init()
* @throws Exception {
*/ $this->event = Snowflake::app()->getEvent();
public function onHandler(Request $request, Response $response): mixed $this->router = Snowflake::app()->getRouter();
{ }
try {
defer(function () {
fire(Event::SYSTEM_RESOURCE_RELEASES);
});
/** @var HRequest $request */
[$request, $response] = OnRequest::createContext($request, $response);
$this->event->dispatch(Event::EVENT_BEFORE_REQUEST, [$request]);
$result = $request->dispatch();
$this->event->dispatch(Event::EVENT_AFTER_REQUEST, [$request, $result]);
return $result;
} catch (ExitException | Error | \Throwable $exception) {
$this->addError($exception, 'throwable');
return $this->sendErrorMessage($request, $response, $exception);
}
}
/** /**
* @param $request * @param Request $request
* @param $response * @param Response $response
* @return array * @return void
*/ * @throws Exception
public static function createContext($request, $response): array */
{ public function onHandler(Request $request, Response $response): mixed
return [HRequest::create($request), HResponse::create($response)]; {
} try {
defer(function () {
fire(Event::SYSTEM_RESOURCE_RELEASES);
});
/** @var HRequest $request */
/** @var HResponse $response */
[$request, $response] = OnRequest::createContext($request, $response);
if ($request->is('favicon.ico')) {
return $response->send('', 404);
}
return $this->router->dispatch();
} catch (ExitException | Error | \Throwable $exception) {
$this->addError($exception, 'throwable');
return $this->sendErrorMessage($request, $response, $exception);
}
}
/** /**
* @param $sRequest * @param $request
* @param $sResponse * @param $response
* @param $exception * @return array
* @return bool|string */
* @throws Exception public static function createContext($request, $response): array
*/ {
protected function sendErrorMessage($sRequest, $sResponse, $exception): bool|string return [HRequest::create($request), HResponse::create($response)];
{ }
$this->addError($exception, 'throwable');
if ($sResponse instanceof Response) {
[$sRequest, $sResponse] = [HRequest::create($sRequest), HResponse::create($sResponse)];
}
$this->event->dispatch(Event::EVENT_AFTER_REQUEST, [$sRequest, $exception]);
$headers = $sRequest->headers->get('access-control-request-headers'); /**
$methods = $sRequest->headers->get('access-control-request-method'); * @param $sRequest
* @param $sResponse
* @param $exception
* @return bool|string
* @throws Exception
*/
protected function sendErrorMessage($sRequest, $sResponse, $exception): bool|string
{
$this->addError($exception, 'throwable');
if ($sResponse instanceof Response) {
[$sRequest, $sResponse] = [HRequest::create($sRequest), HResponse::create($sResponse)];
}
$sResponse->addHeader('Access-Control-Allow-Origin', '*'); $this->event->dispatch(Event::EVENT_AFTER_REQUEST, [$sRequest, $exception]);
$sResponse->addHeader('Access-Control-Allow-Headers', $headers);
$sResponse->addHeader('Access-Control-Request-Method', $methods);
if (!($exception instanceof ExitException)) { $headers = $sRequest->headers->get('access-control-request-headers');
return $sResponse->send(\logger()->exception($exception), 200); $methods = $sRequest->headers->get('access-control-request-method');
} else {
return $sResponse->send($exception->getMessage(), 200); $sResponse->addHeader('Access-Control-Allow-Origin', '*');
} $sResponse->addHeader('Access-Control-Allow-Headers', $headers);
} $sResponse->addHeader('Access-Control-Request-Method', $methods);
if (!($exception instanceof ExitException)) {
return $sResponse->send(\logger()->exception($exception), 200);
} else {
return $sResponse->send($exception->getMessage(), 200);
}
}
} }
+455 -454
View File
@@ -31,539 +31,540 @@ use function Input;
class Node extends HttpService class Node extends HttpService
{ {
public string $path = ''; public string $path = '';
public int $index = 0; public int $index = 0;
public string $method = ''; public string $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 array $rules = []; private array $rules = [];
private string $_dataType = ''; private string $_dataType = '';
/** @var ?Closure|?array */ /** @var ?Closure|?array */
public Closure|array|null $handler; public Closure|array|null $handler;
public string $htmlSuffix = '.html'; public string $htmlSuffix = '.html';
public bool $enableHtmlSuffix = false; public bool $enableHtmlSuffix = false;
public array $namespace = []; public array $namespace = [];
public array $middleware = []; public array $middleware = [];
/** @var array|Closure */ /** @var array|Closure */
public Closure|array $callback = []; public Closure|array $callback = [];
private string $_alias = ''; private string $_alias = '';
private array $_interceptors = []; private array $_interceptors = [];
private array $_after = []; private array $_after = [];
private array $_limits = []; private array $_limits = [];
/** /**
* @param string $dataType * @param string $dataType
*/ */
public function setDataType(string $dataType) public function setDataType(string $dataType)
{ {
$this->_dataType = $dataType; $this->_dataType = $dataType;
} }
/** /**
* @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 == RpcProducer::PROTOCOL_JSON) { if ($this->_dataType == RpcProducer::PROTOCOL_JSON) {
return json_decode($data, true); return json_decode($data, true);
} }
if ($this->_dataType == RpcProducer::PROTOCOL_SERIALIZE) { if ($this->_dataType == RpcProducer::PROTOCOL_SERIALIZE) {
return unserialize($data); return unserialize($data);
} }
return $data; return $data;
} }
/** /**
* @param $handler * @param $handler
* @return Node * @return Node
* @throws * @throws
*/ */
public function bindHandler($handler): static public function bindHandler($handler): static
{ {
if (is_string($handler) && str_contains($handler, '@')) { if (is_string($handler) && str_contains($handler, '@')) {
list($controller, $action) = explode('@', $handler); list($controller, $action) = explode('@', $handler);
if (!empty($this->namespace)) { if (!empty($this->namespace)) {
$controller = implode('\\', $this->namespace) . '\\' . $controller; $controller = implode('\\', $this->namespace) . '\\' . $controller;
} }
$this->handler = $this->getReflect($controller, $action); $this->handler = $this->getReflect($controller, $action);
} 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.';
} else if ($handler instanceof Closure) { } else if ($handler instanceof Closure) {
$this->handler = $handler; $this->handler = $handler;
} else { } else {
[$controller, $action] = $this->handler = $handler; [$controller, $action] = $this->handler = $handler;
if (!($controller instanceof Controller)) { if (!($controller instanceof Controller)) {
return $this; return $this;
} }
$this->annotationInject($controller::class, $action); $this->annotationInject($controller::class, $action);
} }
if (!empty($this->handler)) { if (!empty($this->handler)) {
$this->callback = Reduce::reduce($this->createDispatch(), $this->annotation()); $this->callback = Reduce::reduce($this->createDispatch(), $this->annotation());
} }
return $this; return $this;
} }
/** /**
* @return Closure * @return Closure
*/ */
public function createDispatch(): Closure public function createDispatch(): Closure
{ {
return function () { return function () {
$dispatchParam = Context::getContext('dispatch-param'); $dispatchParam = Context::getContext('dispatch-param');
if (empty($dispatchParam)) { if (empty($dispatchParam)) {
$dispatchParam = [\request()]; $dispatchParam = [\request()];
} }
// return call_user_func($this->handler, ...$dispatchParam); // return call_user_func($this->handler, ...$dispatchParam);
return \aop($this->handler, $dispatchParam); return \aop($this->handler, $dispatchParam);
}; };
} }
/** /**
* @return array * @return array
*/ */
protected function annotation(): array protected function annotation(): array
{ {
$middleWares = $this->getMiddleWares(); $middleWares = $this->getMiddleWares();
$middleWares = $this->annotation_limit($this, $middleWares); $middleWares = $this->annotation_limit($this, $middleWares);
$middleWares = $this->annotation_interceptor($this, $middleWares); $middleWares = $this->annotation_interceptor($this, $middleWares);
return $middleWares; return $middleWares;
} }
/** /**
* @param Node $node * @param Node $node
* @param $middleWares * @param $middleWares
* @return array * @return array
*/ */
protected function annotation_interceptor(Node $node, $middleWares = []): array protected function annotation_interceptor(Node $node, $middleWares = []): array
{ {
if (!$node->hasInterceptor()) { if (!$node->hasInterceptor()) {
return $middleWares; return $middleWares;
} }
foreach ($node->getInterceptor() as $item) { foreach ($node->getInterceptor() as $item) {
$middleWares[] = $item; $middleWares[] = $item;
} }
return $middleWares; return $middleWares;
} }
/** /**
* @param Node $node * @param Node $node
* @param $middleWares * @param $middleWares
* @return array * @return array
*/ */
protected function annotation_limit(Node $node, $middleWares = []): array protected function annotation_limit(Node $node, $middleWares = []): array
{ {
if (!$node->hasLimits()) { if (!$node->hasLimits()) {
return $middleWares; return $middleWares;
} }
foreach ($node->getLimits() as $item) { foreach ($node->getLimits() as $item) {
$middleWares[] = $item; $middleWares[] = $item;
} }
return $middleWares; return $middleWares;
} }
/** /**
* @return bool * @return bool
*/ */
#[Pure] public function hasInterceptor(): bool #[Pure] public function hasInterceptor(): bool
{ {
return count($this->_interceptors) > 0; return count($this->_interceptors) > 0;
} }
/** /**
* @return bool * @return bool
*/ */
#[Pure] public function hasLimits(): bool #[Pure] public function hasLimits(): bool
{ {
return count($this->_limits) > 0; return count($this->_limits) > 0;
} }
/** /**
* @param null $response * @param null $response
* @return mixed * @return mixed
* @throws Exception * @throws Exception
*/ */
public function afterDispatch($response = null): mixed public function afterDispatch($response = null): mixed
{ {
if (is_object($this->_after[0])) { if (is_object($this->_after[0])) {
return call_user_func($this->_after, \request(), $response); return call_user_func($this->_after, \request(), $response);
} }
foreach ($this->_after as $value) { foreach ($this->_after as $value) {
call_user_func($value, \request(), $response); call_user_func($value, \request(), $response);
} }
return $this->_after; return $this->_after;
} }
/** /**
* @return array * @return array
*/ */
public function getInterceptor(): array public function getInterceptor(): array
{ {
return $this->_interceptors; return $this->_interceptors;
} }
/** /**
* @return array * @return array
*/ */
public function getAfters(): array public function getAfters(): array
{ {
return $this->_after; return $this->_after;
} }
/** /**
* @return bool * @return bool
*/ */
#[Pure] public function hasAfter(): bool #[Pure] public function hasAfter(): bool
{ {
return count($this->_after) > 0; return count($this->_after) > 0;
} }
/** /**
* @return array * @return array
*/ */
public function getLimits(): array public function getLimits(): array
{ {
return $this->_limits; return $this->_limits;
} }
/** /**
* @param $request * @param $request
* @return bool * @return bool
*/ */
public function methodAllow(Request $request): bool public function methodAllow(Request $request): bool
{ {
if ($this->method == $request->getMethod()) { if ($this->method == $request->getMethod()) {
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(); $url = request()->getUri();
$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;
} }
/** /**
* @param string $controller * @param string $controller
* @param string $action * @param string $action
* @return null|array * @return null|array
* @throws Exception * @throws Exception
*/ */
private function getReflect(string $controller, string $action): ?array private function getReflect(string $controller, string $action): ?array
{ {
try { try {
$reflect = Snowflake::getDi()->getReflect($controller); $reflect = Snowflake::getDi()->getReflect($controller);
if (empty($reflect)) { if (empty($reflect)) {
throw new Exception($controller . ' Class is con\'t Instantiable.'); throw new Exception($controller . ' Class is con\'t Instantiable.');
} }
if (!empty($action) && !$reflect->hasMethod($action)) { if (!empty($action) && !$reflect->hasMethod($action)) {
throw new Exception('method ' . $action . ' not exists at ' . $controller . '.'); throw new Exception('method ' . $action . ' not exists at ' . $controller . '.');
} }
$this->annotationInject($reflect->getName(), $action); $this->annotationInject($reflect->getName(), $action);
return [$reflect->newInstance(), $action]; return [$reflect->newInstance(), $action];
} catch (Throwable $exception) { } catch (Throwable $exception) {
$this->_error = $exception->getMessage(); $this->_error = $exception->getMessage();
$this->addError($exception, 'router'); $this->addError($exception, 'router');
return null; return null;
} }
} }
/** /**
* @param Closure|array|string $handler * @param Closure|array|string $handler
* @throws Exception * @throws Exception
*/ */
public function addInterceptor(Closure|string|array $handler) public function addInterceptor(Closure|string|array $handler)
{ {
if (!is_array($handler) || is_object($handler[0])) { if (!is_array($handler) || is_object($handler[0])) {
$handler = [$handler]; $handler = [$handler];
} }
foreach ($handler as $closure) { foreach ($handler as $closure) {
if (in_array($closure, $this->_interceptors)) { if (in_array($closure, $this->_interceptors)) {
continue; continue;
} }
$this->_interceptors[] = $closure; $this->_interceptors[] = $closure;
} }
} }
/** /**
* @param string $className * @param string $className
* @param string $action * @param string $action
* @return Node * @return Node
* @throws Exception * @throws Exception
*/ */
public function annotationInject(string $className, string $action): Node public function annotationInject(string $className, string $action): Node
{ {
$annotation = annotation()->getMethods($className, $action); $annotation = annotation()->getMethods($className, $action);
if (empty($annotation)) { if (empty($annotation)) {
return $this->injectRules($className, $action); return $this->injectRules($className, $action);
} }
foreach ($annotation as $attribute) { foreach ($annotation as $attribute) {
if ($attribute instanceof Interceptor) { if ($attribute instanceof Interceptor) {
$this->addInterceptor($attribute->interceptor); $this->addInterceptor($attribute->interceptor);
} }
if ($attribute instanceof After) { if ($attribute instanceof After) {
$this->addAfter($attribute->after); $this->addAfter($attribute->after);
} }
if ($attribute instanceof Middleware) { if ($attribute instanceof Middleware) {
$this->addMiddleware($attribute->middleware); $this->addMiddleware($attribute->middleware);
} }
if ($attribute instanceof Limits) { if ($attribute instanceof Limits) {
$this->addLimits($attribute->limits); $this->addLimits($attribute->limits);
} }
} }
return $this->injectRules($className, $action); return $this->injectRules($className, $action);
} }
/** /**
* @param string $controller * @param string $controller
* @param string $action * @param string $action
* @return $this * @return $this
* @throws \Exception * @throws \Exception
*/ */
private function injectRules(string $controller, string $action): static private function injectRules(string $controller, string $action): static
{ {
/** @var HttpFilter $filter */ /** @var HttpFilter $filter */
$filter = Snowflake::app()->get('filter'); $filter = Snowflake::app()->get('filter');
$this->rules = $filter->getRules($controller, $action); $this->rules = $filter->getRules($controller, $action);
return $this; return $this;
} }
/** /**
* @param Closure|array|string $handler * @param Closure|array|string $handler
* @throws Exception * @throws Exception
*/ */
public function addAfter(Closure|string|array $handler) public function addAfter(Closure|string|array $handler)
{ {
if (!is_array($handler) || is_object($handler[0])) { if (!is_array($handler) || is_object($handler[0])) {
$handler = [$handler]; $handler = [$handler];
} }
foreach ($handler as $closure) { foreach ($handler as $closure) {
if (in_array($closure, $this->_after)) { if (in_array($closure, $this->_after)) {
continue; continue;
} }
$this->_after[] = $closure; $this->_after[] = $closure;
} }
} }
/** /**
* @param Closure|array|string $handler * @param Closure|array|string $handler
* @throws Exception * @throws Exception
*/ */
public function addLimits(Closure|string|array $handler) public function addLimits(Closure|string|array $handler)
{ {
if (!is_array($handler) || is_object($handler[0])) { if (!is_array($handler) || is_object($handler[0])) {
$handler = [$handler]; $handler = [$handler];
} }
foreach ($handler as $closure) { foreach ($handler as $closure) {
if (in_array($closure, $this->_limits)) { if (in_array($closure, $this->_limits)) {
continue; continue;
} }
$this->_limits[] = $closure; $this->_limits[] = $closure;
} }
} }
/** /**
* @return string * @return string
* 错误信息 * 错误信息
*/ */
public function getError(): string public function getError(): string
{ {
return $this->_error; return $this->_error;
} }
/** /**
* @param Node $node * @param Node $node
* @param string $field * @param string $field
* @return Node * @return Node
*/ */
public function addChild(Node $node, string $field): Node public function addChild(Node $node, string $field): Node
{ {
$field = (string)$field; $field = (string)$field;
/** @var Node $oLod */ /** @var Node $oLod */
$oLod = $this->childes[$field] ?? null; $oLod = $this->childes[$field] ?? null;
if (!empty($oLod)) { if (!empty($oLod)) {
$node = $oLod; $node = $oLod;
} }
$this->childes[$field] = $node; $this->childes[$field] = $node;
return $this->childes[$field]; return $this->childes[$field];
} }
/** /**
* @param string $search * @param string $search
* @return Node|null * @return Node|null
*/ */
public function findNode(string $search): ?Node public function findNode(string $search): ?Node
{ {
if (empty($this->childes)) { if (empty($this->childes)) {
return null; return null;
} }
if (isset($this->childes[$search])) { if (isset($this->childes[$search])) {
return $this->childes[$search]; return $this->childes[$search];
} }
$_searchMatch = '/<(\w+)?:(.+)?>/'; $_searchMatch = '/<(\w+)?:(.+)?>/';
foreach ($this->childes as $key => $val) { foreach ($this->childes as $key => $val) {
if (preg_match($_searchMatch, (string)$key, $match)) { if (preg_match($_searchMatch, (string)$key, $match)) {
Input()->addGetParam($match[1] ?? '--', $search); Input()->addGetParam($match[1] ?? '--', $search);
return $this->childes[$key]; return $this->childes[$key];
} }
} }
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 Closure|array $class * @param Closure|array $class
* @return $this * @return $this
*/ */
public function addMiddleware(Closure|array $class): static public function addMiddleware(Closure|array $class): static
{ {
if (empty($class)) return $this; if (empty($class)) return $this;
foreach ($class as $closure) { foreach ($class as $closure) {
if (in_array($closure, $this->middleware)) { if (in_array($closure, $this->middleware)) {
continue; continue;
} }
$this->middleware[] = $closure; $this->middleware[] = $closure;
} }
return $this; return $this;
} }
/** /**
* @return array * @return array
*/ */
public function getMiddleWares(): array public function getMiddleWares(): array
{ {
return $this->middleware; return $this->middleware;
} }
/** /**
* @return mixed * @return mixed
* @throws Exception * @throws Exception
*/ */
public function dispatch(): mixed public function dispatch(): mixed
{ {
Context::setContext('dispatch-param', func_get_args()); Context::setContext('dispatch-param', func_get_args());
if (empty($this->callback)) { if (empty($this->callback)) {
return Json::to(404, $this->errorMsg()); return Json::to(404, $this->errorMsg());
} }
return $this->httpFilter(); return call_user_func($this->handler, \request());
} return $this->httpFilter();
}
/** /**
* @return mixed * @return mixed
* @throws Exception * @throws Exception
*/ */
private function httpFilter(): mixed private function httpFilter(): mixed
{ {
if ($this->handler instanceof Closure) { if ($this->handler instanceof Closure) {
return call_user_func($this->handler, \request()); return call_user_func($this->handler, \request());
} else { } else {
return $this->runValidator([\request()]); return $this->runValidator([\request()]);
} }
} }
/** /**
* @param $dispatchParams * @param $dispatchParams
* @return mixed * @return mixed
* @throws Exception * @throws Exception
*/ */
private function runValidator($dispatchParams): mixed private function runValidator($dispatchParams): mixed
{ {
if (empty($this->rules) || !is_array($this->rules)) { if (empty($this->rules) || !is_array($this->rules)) {
return call_user_func($this->callback, ...$dispatchParams); return call_user_func($this->callback, ...$dispatchParams);
} }
/** @var HttpFilter $filter */ /** @var HttpFilter $filter */
$filter = Snowflake::app()->get('filter'); $filter = Snowflake::app()->get('filter');
$validator = $filter->check($this->rules); $validator = $filter->check($this->rules);
if (!($validator instanceof Validator) || $validator->validation()) { if (!($validator instanceof Validator) || $validator->validation()) {
return call_user_func($this->callback, ...$dispatchParams); return call_user_func($this->callback, ...$dispatchParams);
} else { } else {
return Json::to(5005, $validator->getError()); return Json::to(5005, $validator->getError());
} }
} }
/** /**
* @return string * @return string
*/ */
private function errorMsg(): string private function errorMsg(): string
{ {
return $this->_error ?? 'Page not found.'; return $this->_error ?? 'Page not found.';
} }
} }
+1 -2
View File
@@ -540,8 +540,7 @@ class Router extends HttpService implements RouterInterface
if (!($node = $this->find_path(\request()))) { if (!($node = $this->find_path(\request()))) {
return send(self::NOT_FOUND); return send(self::NOT_FOUND);
} }
$response = $node->dispatch(); send(($response = $node->dispatch()), 200);
send($response, 200);
if (!$node->hasAfter()) { if (!$node->hasAfter()) {
return null; return null;
} }