This commit is contained in:
as2252258@163.com
2021-09-05 04:31:27 +08:00
parent 8bb0fe1e68
commit 00a8645ec7
+453 -453
View File
@@ -29,526 +29,526 @@ defined('ROUTER_HASH') or define('ROUTER_HASH', 2);
*/ */
class Router extends HttpService implements RouterInterface class Router extends HttpService implements RouterInterface
{ {
/** @var Node[] $nodes */ /** @var Node[] $nodes */
public array $nodes = []; public array $nodes = [];
public array $groupTacks = []; public array $groupTacks = [];
public ?string $dir = 'App\\Http\\Controllers'; public ?string $dir = 'App\\Http\\Controllers';
const NOT_FOUND = 'Page not found or method not allowed.'; const NOT_FOUND = 'Page not found or method not allowed.';
/** @var string[] */ /** @var string[] */
public array $methods = ['GET', 'POST', 'OPTIONS', 'PUT', 'DELETE', 'RECEIVE', 'HEAD']; public array $methods = ['GET', 'POST', 'OPTIONS', 'PUT', 'DELETE', 'RECEIVE', 'HEAD'];
public ?Closure $middleware = null; public ?Closure $middleware = null;
public int $useTree = ROUTER_TREE; public int $useTree = ROUTER_TREE;
public ?Response $response = null; public ?Response $response = null;
/** /**
* @var RequestInterface * @var RequestInterface
*/ */
#[Inject(RequestInterface::class)] #[Inject(RequestInterface::class)]
public RequestInterface $request; public RequestInterface $request;
/** /**
* @param Closure $middleware * @param Closure $middleware
*/ */
public function setMiddleware(Closure $middleware): void public function setMiddleware(Closure $middleware): void
{ {
$this->middleware = $middleware; $this->middleware = $middleware;
} }
/** /**
* @throws ConfigException * @throws ConfigException
* @throws Exception * @throws Exception
* 初始化函数路径 * 初始化函数路径
*/ */
public function init() public function init()
{ {
$this->dir = Config::get('http.namespace', $this->dir); $this->dir = Config::get('http.namespace', $this->dir);
$this->response = Kiri::app()->get('response'); $this->response = Kiri::app()->get('response');
} }
/** /**
* @param bool $useTree * @param bool $useTree
*/ */
public function setUseTree(bool $useTree): void public function setUseTree(bool $useTree): void
{ {
$this->useTree = $useTree ? ROUTER_TREE : ROUTER_HASH; $this->useTree = $useTree ? ROUTER_TREE : ROUTER_HASH;
} }
/** /**
* @param $path * @param $path
* @param $handler * @param $handler
* @param string $method * @param string $method
* @return ?Node * @return ?Node
* @throws Exception * @throws Exception
*/ */
public function addRoute($path, $handler, string $method = 'any'): ?Node public function addRoute($path, $handler, string $method = 'any'): ?Node
{ {
if ($handler instanceof Closure) { if ($handler instanceof Closure) {
$handler = Closure::bind($handler, di(Controller::class)); $handler = Closure::bind($handler, di(Controller::class));
} }
return $this->tree($path, $handler, $method); return $this->tree($path, $handler, $method);
} }
/** /**
* @param $path * @param $path
* @return string * @return string
*/ */
#[Pure] private function resolve($path): string #[Pure] private function resolve($path): string
{ {
$paths = array_column($this->groupTacks, 'prefix'); $paths = array_column($this->groupTacks, 'prefix');
if (empty($paths)) { if (empty($paths)) {
return '/' . ltrim($path, '/'); return '/' . ltrim($path, '/');
} }
$paths = '/' . implode('/', $paths); $paths = '/' . implode('/', $paths);
if ($path != '/') { if ($path != '/') {
return $paths . '/' . ltrim($path, '/'); return $paths . '/' . ltrim($path, '/');
} }
return $paths . '/'; return $paths . '/';
} }
/** /**
* @param $path * @param $path
* @param $handler * @param $handler
* @param string $method * @param string $method
* @return Node * @return Node
* @throws Exception * @throws Exception
*/ */
private function tree($path, $handler, string $method = 'any'): Node private function tree($path, $handler, string $method = 'any'): Node
{ {
$explode = $this->split($path); $explode = $this->split($path);
$start = array_shift($explode); $start = array_shift($explode);
$parent = $this->nodes[$start] ?? null; $parent = $this->nodes[$start] ?? null;
if (is_null($parent)) { if (is_null($parent)) {
$parent = $this->nodes[$start] = $this->NodeInstance($start, 0, $method); $parent = $this->nodes[$start] = $this->NodeInstance($start, 0, $method);
} }
if (!empty($explode)) { if (!empty($explode)) {
$parent = $this->bindNode($parent, $explode, $method); $parent = $this->bindNode($parent, $explode, $method);
} }
if (!in_array($method, $parent->method)) { if (!in_array($method, $parent->method)) {
$parent->method[] = $method; $parent->method[] = $method;
} }
return $parent->setHandler($handler, $method, $path); return $parent->setHandler($handler, $method, $path);
} }
/** /**
* @param Node $parent * @param Node $parent
* @param array $explode * @param array $explode
* @param $method * @param $method
* @return Node * @return Node
* @throws Exception * @throws Exception
*/ */
private function bindNode(Node $parent, array $explode, $method): Node private function bindNode(Node $parent, array $explode, $method): Node
{ {
$a = 0; $a = 0;
foreach ($explode as $value) { foreach ($explode as $value) {
++$a; ++$a;
$search = $parent->findNode($value); $search = $parent->findNode($value);
if ($search === null) { if ($search === null) {
$parent = $parent->addChild($this->NodeInstance($value, $a, $method)); $parent = $parent->addChild($this->NodeInstance($value, $a, $method));
} else { } else {
$parent = $search; $parent = $search;
} }
} }
return $parent; return $parent;
} }
/** /**
* @param $route * @param $route
* @param $handler * @param $handler
* @return void * @return void
* @throws * @throws
*/ */
public function socket($route, $handler): void public function socket($route, $handler): void
{ {
$this->addRoute($route, $handler, 'SOCKET'); $this->addRoute($route, $handler, 'SOCKET');
} }
/** /**
* @param $route * @param $route
* @param $handler * @param $handler
* @return void * @return void
* @throws * @throws
*/ */
public function post($route, $handler): void public function post($route, $handler): void
{ {
$this->addRoute($route, $handler, 'POST'); $this->addRoute($route, $handler, 'POST');
} }
/** /**
* @param $route * @param $route
* @param $handler * @param $handler
* @return void * @return void
* @throws * @throws
*/ */
public function get($route, $handler): void public function get($route, $handler): void
{ {
$this->addRoute($route, $handler, 'GET'); $this->addRoute($route, $handler, 'GET');
} }
/** /**
* @param $route * @param $route
* @param $handler * @param $handler
* @return void * @return void
* @throws * @throws
*/ */
public function options($route, $handler): void public function options($route, $handler): void
{ {
$this->addRoute($route, $handler, 'OPTIONS'); $this->addRoute($route, $handler, 'OPTIONS');
} }
/** /**
* @param $route * @param $route
* @param $handler * @param $handler
* @throws * @throws
*/ */
public function any($route, $handler): void public function any($route, $handler): void
{ {
foreach ($this->methods as $method) { foreach ($this->methods as $method) {
$this->addRoute($route, $handler, $method); $this->addRoute($route, $handler, $method);
} }
} }
/** /**
* @param $route * @param $route
* @param $handler * @param $handler
* @return void * @return void
* @throws * @throws
*/ */
public function delete($route, $handler): void public function delete($route, $handler): void
{ {
$this->addRoute($route, $handler, 'DELETE'); $this->addRoute($route, $handler, 'DELETE');
} }
/** /**
* @param $route * @param $route
* @param $handler * @param $handler
* @return void * @return void
* @throws Exception * @throws Exception
*/ */
public function head($route, $handler): void public function head($route, $handler): void
{ {
$this->addRoute($route, $handler, 'HEAD'); $this->addRoute($route, $handler, 'HEAD');
} }
/** /**
* @param $route * @param $route
* @param $handler * @param $handler
* @return void * @return void
* @throws * @throws
*/ */
public function put($route, $handler): void public function put($route, $handler): void
{ {
$this->addRoute($route, $handler, 'PUT'); $this->addRoute($route, $handler, 'PUT');
} }
/** /**
* @param $value * @param $value
* @param int $index * @param int $index
* @param string $method * @param string $method
* @return Node * @return Node
* @throws * @throws
*/ */
public function NodeInstance($value, int $index = 0, string $method = 'GET'): Node public function NodeInstance($value, int $index = 0, string $method = 'GET'): Node
{ {
$node = new Node($this); $node = new Node($this);
$node->childes = []; $node->childes = [];
$node->path = $value; $node->path = $value;
$node->index = $index; $node->index = $index;
$node->method[] = $method; $node->method[] = $method;
$node->namespace = $this->loadNamespace(); $node->namespace = $this->loadNamespace();
$name = array_column($this->groupTacks, 'middleware'); $name = array_column($this->groupTacks, 'middleware');
if (is_array($name)) { if (is_array($name)) {
$node->addMiddleware($method, $this->resolve_middleware($name)); $node->addMiddleware($method, $this->resolve_middleware($name));
} }
return $node; return $node;
} }
/** /**
* @return Closure * @return Closure
*/ */
public function getMiddleware(): ?Closure public function getMiddleware(): ?Closure
{ {
return $this->middleware; return $this->middleware;
} }
/** /**
* @param string|array $middleware * @param string|array $middleware
* @return array * @return array
* @throws NotFindClassException * @throws NotFindClassException
* @throws ReflectionException * @throws ReflectionException
*/ */
private function resolve_middleware(string|array $middleware): array private function resolve_middleware(string|array $middleware): array
{ {
if (is_string($middleware)) { if (is_string($middleware)) {
$middleware = [$middleware]; $middleware = [$middleware];
} }
$array = []; $array = [];
foreach ($middleware as $value) { foreach ($middleware as $value) {
if (is_array($value)) { if (is_array($value)) {
foreach ($value as $item) { foreach ($value as $item) {
$array[] = $this->getMiddlewareInstance($item); $array[] = $this->getMiddlewareInstance($item);
} }
} else { } else {
$array[] = $this->getMiddlewareInstance($value); $array[] = $this->getMiddlewareInstance($value);
} }
} }
return array_filter($array); return array_filter($array);
} }
/** /**
* @param $value * @param $value
* @return Closure|array|null * @return Closure|array|null
* @throws NotFindClassException * @throws NotFindClassException
* @throws ReflectionException * @throws ReflectionException
*/ */
private function getMiddlewareInstance($value): null|Closure|array private function getMiddlewareInstance($value): null|Closure|array
{ {
if (!is_string($value)) { if (!is_string($value)) {
return $value; return $value;
} }
$value = Kiri::createObject($value); $value = Kiri::createObject($value);
if (!($value instanceof MiddlewareInterface)) { if (!($value instanceof MiddlewareInterface)) {
return null; return null;
} }
return [$value, 'onHandler']; return [$value, 'onHandler'];
} }
/** /**
* @return array * @return array
*/ */
private function loadNamespace(): array private function loadNamespace(): array
{ {
$name = array_column($this->groupTacks, 'namespace'); $name = array_column($this->groupTacks, 'namespace');
array_unshift($name, $this->dir); array_unshift($name, $this->dir);
return array_filter($name); return array_filter($name);
} }
/** /**
* @param array $config * @param array $config
* @param callable $callback * @param callable $callback
* 路由分组 * 路由分组
* @param null $stdClass * @param null $stdClass
*/ */
public function group(array $config, callable $callback, $stdClass = null) public function group(array $config, callable $callback, $stdClass = null)
{ {
$this->groupTacks[] = $config; $this->groupTacks[] = $config;
if ($stdClass) { if ($stdClass) {
$callback($stdClass); $callback($stdClass);
} else { } else {
$callback($this); $callback($this);
} }
array_pop($this->groupTacks); array_pop($this->groupTacks);
} }
/** /**
* @return string * @return string
*/ */
public function addPrefix(): string public function addPrefix(): string
{ {
$prefix = array_column($this->groupTacks, 'prefix'); $prefix = array_column($this->groupTacks, 'prefix');
$prefix = array_filter($prefix); $prefix = array_filter($prefix);
if (empty($prefix)) { if (empty($prefix)) {
return ''; return '';
} }
return '/' . implode('/', $prefix); return '/' . implode('/', $prefix);
} }
/** /**
* @param array|null $explode * @param array|null $explode
* @return Node|null * @return Node|null
* 查找指定路由 * 查找指定路由
* @throws Exception * @throws Exception
*/ */
public function tree_search(?array $explode): ?Node public function tree_search(?array $explode): ?Node
{ {
if (empty($this->nodes)) { if (empty($this->nodes)) {
return null; return null;
} }
$parent = $this->nodes[array_shift($explode)] ?? null; $parent = $this->nodes[array_shift($explode)] ?? null;
if (!($parent instanceof Node)) { if (!($parent instanceof Node)) {
return null; return null;
} }
while ($value = array_shift($explode)) { while ($value = array_shift($explode)) {
$node = $parent->findNode($value); $node = $parent->findNode($value);
if (!$node) { if (!$node) {
return null; return null;
} }
$parent = $node; $parent = $node;
} }
return $parent; return $parent;
} }
/** /**
* @param $path * @param $path
* @return array|null * @return array|null
*/ */
public function split($path): ?array public function split($path): ?array
{ {
$path = $this->addPrefix() . '/' . ltrim($path, '/'); $path = $this->addPrefix() . '/' . ltrim($path, '/');
if ($path === '/') { if ($path === '/') {
return ['/']; return ['/'];
} }
$filter = array_filter(explode('/', $path)); $filter = array_filter(explode('/', $path));
if (!empty($filter)) { if (!empty($filter)) {
return $filter; return $filter;
} }
return ['/']; return ['/'];
} }
/** /**
* @return array * @return array
*/ */
public function each(): array public function each(): array
{ {
$paths = []; $paths = [];
foreach ($this->nodes as $_node) { foreach ($this->nodes as $_node) {
/** @var Node[] $node */ /** @var Node[] $node */
$paths[] = ['method' => $_node->method, 'path' => $_node->sourcePath, 'alias' => $_node->getAlias()]; $paths[] = ['method' => $_node->method, 'path' => $_node->sourcePath, 'alias' => $_node->getAlias()];
$paths = $this->getChildes($_node, $paths); $paths = $this->getChildes($_node, $paths);
} }
return $paths; return $paths;
} }
/** /**
* @param Node $node * @param Node $node
* @param array $path * @param array $path
* @return array * @return array
*/ */
private function getChildes(Node $node, array $path): array private function getChildes(Node $node, array $path): array
{ {
foreach ($node->childes as $item) { foreach ($node->childes as $item) {
$path[] = ['method' => $item->method, 'path' => $item->sourcePath, 'alias' => $item->getAlias()]; $path[] = ['method' => $item->method, 'path' => $item->sourcePath, 'alias' => $item->getAlias()];
if (!empty($item->childes)) { if (!empty($item->childes)) {
$path = $this->getChildes($item, $path); $path = $this->getChildes($item, $path);
} }
} }
return $path; return $path;
} }
/** /**
* @param $exception * @param $exception
* @return mixed * @return mixed
* @throws Exception * @throws Exception
*/ */
public function exception($exception): mixed public function exception($exception): mixed
{ {
return Kiri::app()->getLogger()->exception($exception); return Kiri::app()->getLogger()->exception($exception);
} }
/** /**
* @param $uri * @param $uri
* @param $method * @param $method
* @return Node|null * @return Node|null
*/ */
public function search($uri, $method): Node|null public function search($uri, $method): Node|null
{ {
if (!isset($this->nodes[$method])) { if (!isset($this->nodes[$method])) {
return null;
}
$methods = $this->nodes[$method];
if (isset($methods[$uri])) {
return $methods[$uri];
}
return $methods['/'] ?? null;
}
/**
* @param RequestInterface $request
* @return Node|null
* 树杈搜索
* @throws Exception
*/
public function Branch_search(RequestInterface $request): ?Node
{
$uri = $request->getUri();
$node = $this->tree_search($uri->getExplode());
if ($node instanceof Node) {
return $node;
}
if (!$request->isMethod('OPTIONS')) {
return null; return null;
} }
$node = $this->tree_search(['*']); $methods = $this->nodes[$method];
if (!($node instanceof Node)) { if (isset($methods[$uri])) {
return null; return $methods[$uri];
} }
return $node; return $methods['/'] ?? null;
} }
/** /**
* @throws * @param RequestInterface $request
*/ * @return Node|null
public function _loader() * 树杈搜索
{ * @throws Exception
$this->loadRouteDir(APP_PATH . 'routes'); */
} public function Branch_search(RequestInterface $request): ?Node
{
/** $uri = $request->getUri();
* @param $path if ($request->isMethod('OPTIONS')) {
* @throws Exception $node = $this->tree_search(['*']);
* 加载目录下的路由文件 if (!($node instanceof Node)) {
*/ $node = $this->tree_search($uri->getExplode());
private function loadRouteDir($path) }
{ } else {
$files = glob($path . '/*'); $node = $this->tree_search($uri->getExplode());
for ($i = 0; $i < count($files); $i++) { }
if (is_dir($files[$i])) { if (!($node instanceof Node)) {
$this->loadRouteDir($files[$i]); return null;
} else { }
$this->loadRouterFile($files[$i]); return $node;
} }
}
}
/** /**
* @param $files * @throws
* @throws Exception */
*/ public function _loader()
private function loadRouterFile($files) {
{ $this->loadRouteDir(APP_PATH . 'routes');
try { }
$router = $this;
include_once "$files"; /**
} catch (Throwable $exception) { * @param $path
$this->addError($exception, 'throwable'); * @throws Exception
} finally { * 加载目录下的路由文件
if (isset($exception)) { */
unset($exception); private function loadRouteDir($path)
} {
} $files = glob($path . '/*');
} for ($i = 0; $i < count($files); $i++) {
if (is_dir($files[$i])) {
$this->loadRouteDir($files[$i]);
} else {
$this->loadRouterFile($files[$i]);
}
}
}
/**
* @param $files
* @throws Exception
*/
private function loadRouterFile($files)
{
try {
$router = $this;
include_once "$files";
} catch (Throwable $exception) {
$this->addError($exception, 'throwable');
} finally {
if (isset($exception)) {
unset($exception);
}
}
}
} }