This commit is contained in:
2021-08-17 16:43:50 +08:00
parent 539ba488e9
commit 5b1e28c323
80 changed files with 232 additions and 396 deletions
+40
View File
@@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
namespace Http\Route;
/**
* Class Any
* @package Kiri\Kiri\Route
*/
class Any
{
private array $nodes = [];
/**
* Any constructor.
* @param array $nodes
*/
public function __construct(array $nodes)
{
$this->nodes = $nodes;
}
/**
* @param $name
* @param $arguments
* @return $this
*/
public function __call($name, $arguments): static
{
foreach ($this->nodes as $node) {
$node->{$name}(...$arguments);
}
return $this;
}
}
+47
View File
@@ -0,0 +1,47 @@
<?php
declare(strict_types=1);
namespace Http\Route;
use Closure;
use Exception;
use Http\Http\Context;
use Http\Http\Request;
use Http\Http\Response;
use Http\IInterface\Middleware;
use Server\RequestInterface;
use Kiri\Kiri;
/**
* Class CoreMiddleware
* @package Kiri\Kiri\Route
* 跨域中间件
*/
class CoreMiddleware implements Middleware
{
/** @var int */
public int $zOrder = 0;
/**
* @param Request $request
* @param Closure $next
* @return mixed
* @throws Exception
*/
public function onHandler(RequestInterface $request, Closure $next): mixed
{
/** @var Response $response */
$response = \response();
$response->addHeader('Access-Control-Allow-Origin', '*');
$response->addHeader('Access-Control-Allow-Headers', $request->header('access-control-request-headers'));
$response->addHeader('Access-Control-Request-Method', $request->header('access-control-request-method'));
return $next($request);
}
}
+38
View File
@@ -0,0 +1,38 @@
<?php
namespace Http\Route;
use Kiri\Abstracts\BaseObject;
/**
*
*/
class HandlerProviders extends BaseObject
{
private array $handlers = [];
/**
* @param $path
* @param $method
* @return mixed
*/
public function get($path, $method): mixed
{
return $this->handlers[$method][$path] ?? null;
}
/**
* @param $method
* @param $path
* @param $handler
*/
public function add($method, $path, $handler)
{
$this->handlers[$method][$path] = $handler;
}
}
+106
View File
@@ -0,0 +1,106 @@
<?php
namespace Http\Route;
use Closure;
use Http\IInterface\Middleware;
use Kiri\Abstracts\BaseObject;
/**
* Class MiddlewareManager
* @package Http\Route
*/
class MiddlewareManager extends BaseObject
{
private static array $_middlewares = [];
/**
* @param $class
* @param $method
* @param array|string $middlewares
*/
public function addMiddlewares($class, $method, array|string $middlewares)
{
if (is_object($class)) {
$class = $class::class;
}
if (!isset(static::$_middlewares[$class . '::' . $method])) {
static::$_middlewares[$class . '::' . $method] = [];
}
if (is_string($middlewares) && !in_array($middlewares, static::$_middlewares[$class . '::' . $method])) {
static::$_middlewares[$class . '::' . $method][] = $middlewares;
return;
}
foreach ($middlewares as $middleware) {
if (in_array($middlewares, static::$_middlewares[$class . '::' . $method])) {
continue;
}
static::$_middlewares[$class . '::' . $method][] = $middleware;
}
}
/**
* @param $class
* @param $method
* @return bool
*/
public function hasMiddleware($class, $method): bool
{
if (is_object($class)) {
$class = $class::class;
}
return isset(static::$_middlewares[$class . '::' . $method]);
}
/**
* @param $class
* @param $method
* @param $caller
* @return mixed
*/
public function callerMiddlewares($class, $method, $caller): mixed
{
if (is_object($class)) {
$class = $class::class;
}
$middlewares = static::$_middlewares[$class . '::' . $method] ?? [];
if (empty($middlewares)) {
return $caller;
}
return array_reduce(array_reverse($middlewares), function ($stack, $pipe) {
return function ($passable) use ($stack, $pipe) {
if ($pipe instanceof Middleware) {
return $pipe->onHandler($passable, $stack);
}
return call_user_func($pipe, $passable, $stack);
};
}, $caller);
}
/**
* @param $middlewares
* @param Closure $caller
* @return Closure
*/
public function closureMiddlewares($middlewares, Closure $caller): Closure
{
return array_reduce(array_reverse($middlewares), function ($stack, $pipe) {
return function ($passable) use ($stack, $pipe) {
if ($pipe instanceof Middleware) {
return $pipe->onHandler($passable, $stack);
}
return call_user_func($pipe, $passable, $stack);
};
}, $caller);
}
}
+401
View File
@@ -0,0 +1,401 @@
<?php
declare(strict_types=1);
namespace Http\Route;
use Annotation\Aspect;
use Closure;
use Exception;
use Http\Exception\RequestException;
use Http\Http\Request;
use JetBrains\PhpStorm\Pure;
use ReflectionException;
use Server\Events\OnAfterWorkerStart;
use Kiri\Events\EventProvider;
use Kiri\Exception\NotFindClassException;
use Kiri\IAspect;
use Kiri\Kiri;
/**
* Class Node
* @package Kiri\Kiri\Route
*/
class Node
{
public string $path = '';
public int $index = 0;
public string $method = '';
/** @var Node[] $childes */
public array $childes = [];
public array $group = [];
private string $_error = '';
private string $_dataType = '';
private array|Closure|null $_handler = null;
public string $htmlSuffix = '.html';
public bool $enableHtmlSuffix = false;
public array $namespace = [];
public array $middleware = [];
public string $sourcePath = '';
/** @var array|Closure */
public Closure|array $callback = [];
private string $_alias = '';
/**
* @param string $dataType
*/
public function setDataType(string $dataType)
{
$this->_dataType = $dataType;
}
/**
* @throws NotFindClassException
* @throws ReflectionException
*/
public function __construct()
{
$eventDispatcher = di(EventProvider::class);
$eventDispatcher->on(OnAfterWorkerStart::class, [$this, 'setParameters']);
}
/**
* @param string $data
* @return mixed
*/
public function unpack(string $data): mixed
{
// if ($this->_dataType == RpcProducer::PROTOCOL_JSON) {
// return json_decode($data, true);
// }
// if ($this->_dataType == RpcProducer::PROTOCOL_SERIALIZE) {
// return unserialize($data);
// }
return $data;
}
/**
* @param $handler
* @param $path
* @return Node
* @throws NotFindClassException
* @throws ReflectionException
*/
public function setHandler($handler, $path): static
{
$this->sourcePath = $path;
if (is_string($handler) && str_contains($handler, '@')) {
$handler = $this->splitHandler($handler);
} else if ($handler != null && !is_callable($handler, true)) {
$this->_error = 'Controller is con\'t exec.';
}
$this->_handler = $handler;
return $this;
}
/**
* @param string $handler
* @return array
* @throws NotFindClassException
* @throws ReflectionException
*/
private function splitHandler(string $handler): array
{
list($controller, $action) = explode('@', $handler);
if (!class_exists($controller) && !empty($this->namespace)) {
$controller = implode('\\', $this->namespace) . '\\' . $controller;
}
return [Kiri::getDi()->get($controller), $action];
}
/**
* @throws NotFindClassException
* @throws ReflectionException
*/
private function injectMiddleware($handler): static
{
$manager = di(MiddlewareManager::class);
if (!($handler instanceof Closure)) {
$callback = $this->injectControllerMiddleware($manager, $handler);
} else {
$callback = $this->injectClosureMiddleware($manager, $handler);
}
$this->getHandlerProviders()->add($this->method, $this->sourcePath, $callback);
return $this;
}
/**
* @return HandlerProviders
* @throws NotFindClassException
* @throws ReflectionException
*/
private function getHandlerProviders(): HandlerProviders
{
return Kiri::getDi()->get(HandlerProviders::class);
}
/**
* @param $manager
* @param $handler
* @return mixed
* @throws NotFindClassException
* @throws ReflectionException
*/
private function injectControllerMiddleware($manager, $handler): mixed
{
$manager->addMiddlewares($handler[0], $handler[1], $this->middleware);
return $manager->callerMiddlewares(
$handler[0], $handler[1], $this->aopHandler($this->getAop($handler), $handler)
);
}
/**
* @param $manager
* @param $handler
* @return mixed
*/
private function injectClosureMiddleware($manager, $handler): mixed
{
if (!empty($this->middleware)) {
return $manager->closureMiddlewares($this->middleware, $this->normalHandler($handler));
} else {
return $this->normalHandler($handler);
}
}
private ?array $_injectParameters = [];
/**
* @throws ReflectionException
* @throws NotFindClassException
*/
public function setParameters(): static
{
$container = Kiri::getDi();
if (empty($this->_handler)) {
return $this;
}
$dispatcher = $this->_handler;
if ($dispatcher instanceof Closure) {
$this->_injectParameters = $container->resolveFunctionParameters($dispatcher);
} else {
[$controller, $action] = $dispatcher;
if (is_object($controller)) {
$controller = get_class($controller);
}
$this->_injectParameters = $container->getMethodParameters($controller, $action);
}
return $this->injectMiddleware($dispatcher);
}
/**
* @param IAspect|null $reflect
* @param $handler
* @return Closure
*/
#[Pure] private function aopHandler(?IAspect $reflect, $handler): Closure
{
if (is_null($reflect)) {
return $this->normalHandler($handler);
}
$params = $this->_injectParameters;
return static function () use ($reflect, $handler, $params) {
return $reflect->invoke($handler, $params);
};
}
/**
* @throws ReflectionException|NotFindClassException
*/
private function getAop($handler): ?IAspect
{
[$controller, $action] = $handler;
$aspect = Kiri::getDi()->getMethodAttribute($controller::class, $action);
if (empty($aspect)) {
return null;
}
foreach ($aspect as $value) {
if ($value instanceof Aspect) {
return di($value->aspect);
}
}
return null;
}
/**
* @param $handler
* @return Closure
*/
private function normalHandler($handler): Closure
{
$params = $this->_injectParameters;
return static function () use ($handler, $params) {
return call_user_func($handler, ...$params);
};
}
/**
* @return array
*/
#[Pure] protected function annotation(): array
{
return $this->getMiddleWares();
}
/**
* @param Request $request
* @return bool
*/
public function methodAllow(Request $request): bool
{
if ($this->method == $request->getMethod()) {
return true;
}
return $this->method == 'any';
}
/**
* @return bool
* @throws Exception
*/
public function checkSuffix(): bool
{
if ($this->enableHtmlSuffix) {
$url = request()->getUri();
$nowLength = strlen($this->htmlSuffix);
if (strpos($url, $this->htmlSuffix) !== strlen($url) - $nowLength) {
return false;
}
}
return true;
}
/**
* @return string
* 错误信息
*/
public function getError(): string
{
return $this->_error;
}
/**
* @param Node $node
* @return Node
*/
public function addChild(Node $node): Node
{
$this->childes[] = $node;
return $node;
}
/**
* @param string $search
* @return Node|null
* @throws Exception
*/
public function findNode(string $search): ?Node
{
if (empty($this->childes)) {
return null;
}
foreach ($this->childes as $val) {
if ($search == $val->path) {
return $val;
}
}
return null;
}
/**
* @param string $alias
* @return $this
* 别称
*/
public function alias(string $alias): static
{
$this->_alias = $alias;
return $this;
}
/**
* @return string
*/
public function getAlias(): string
{
return $this->_alias;
}
/**
* @param Closure|array $class
* @return $this
*/
public function addMiddleware(Closure|array $class): static
{
if (empty($class)) return $this;
foreach ($class as $closure) {
if (in_array($closure, $this->middleware)) {
continue;
}
$this->middleware[] = $closure;
}
return $this;
}
/**
* @return array
*/
public function getMiddleWares(): array
{
return $this->middleware;
}
/**
* @return mixed
* @throws Exception
*/
public function dispatch(): mixed
{
$handlerProviders = $this->getHandlerProviders()->get($this->sourcePath, $this->method);
if (empty($handlerProviders)) {
throw new RequestException('<h2>HTTP 404 Not Found</h2><hr><i>Powered by Swoole</i>', 404);
}
return call_user_func($handlerProviders, \request());
}
}
+603
View File
@@ -0,0 +1,603 @@
<?php
declare(strict_types=1);
namespace Http\Route;
use Closure;
use Exception;
use Http\Abstracts\HttpService;
use Http\Controller;
use Http\Exception\RequestException;
use Http\Http\Request;
use Http\Http\Response;
use Http\IInterface\Middleware;
use Http\IInterface\RouterInterface;
use JetBrains\PhpStorm\Pure;
use ReflectionException;
use Server\RequestInterface;
use Kiri\Abstracts\Config;
use Kiri\Exception\ConfigException;
use Kiri\Exception\NotFindClassException;
use Kiri\Kiri;
defined('ROUTER_TREE') or define('ROUTER_TREE', 1);
defined('ROUTER_HASH') or define('ROUTER_HASH', 2);
/**
* Class Router
* @package Kiri\Kiri\Route
*/
class Router extends HttpService implements RouterInterface
{
/** @var Node[] $nodes */
public array $nodes = [];
public array $groupTacks = [];
public ?string $dir = 'App\\Http\\Controllers';
const NOT_FOUND = 'Page not found or method not allowed.';
/** @var string[] */
public array $methods = ['GET', 'POST', 'OPTIONS', 'PUT', 'DELETE', 'RECEIVE', 'HEAD'];
public ?Closure $middleware = null;
public int $useTree = ROUTER_TREE;
public ?Response $response = null;
/**
* @param Closure $middleware
*/
public function setMiddleware(\Closure $middleware): void
{
$this->middleware = $middleware;
}
/**
* @throws ConfigException
* @throws Exception
* 初始化函数路径
*/
public function init()
{
$this->dir = Config::get('http.namespace', $this->dir);
$this->response = Kiri::app()->get('response');
}
/**
* @param bool $useTree
*/
public function setUseTree(bool $useTree): void
{
$this->useTree = $useTree ? ROUTER_TREE : ROUTER_HASH;
}
/**
* @param $path
* @param $handler
* @param string $method
* @return ?Node
* @throws Exception
*/
public function addRoute($path, $handler, string $method = 'any'): ?Node
{
if (!isset($this->nodes[$method])) {
$this->nodes[$method] = [];
}
if ($handler instanceof Closure) {
$handler = Closure::bind($handler, di(Controller::class));
}
return $this->tree($path, $handler, $method);
}
/**
* @param $path
* @param $handler
* @param string $method
* @return ?Node
*/
private function hash($path, $handler, string $method = 'any'): ?Node
{
$path = $this->resolve($path);
$this->nodes[$method][$path] = $this->NodeInstance($path, 0, $method);
return $this->nodes[$method][$path]->setHandler($handler);
}
/**
* @param $path
* @return string
*/
#[Pure] private function resolve($path): string
{
$paths = array_column($this->groupTacks, 'prefix');
if (empty($paths)) {
return '/' . ltrim($path, '/');
}
$paths = '/' . implode('/', $paths);
if ($path != '/') {
return $paths . '/' . ltrim($path, '/');
}
return $paths . '/';
}
/**
* @param $path
* @param $handler
* @param string $method
* @return Node
* @throws Exception
*/
private function tree($path, $handler, string $method = 'any'): Node
{
$explode = $this->split($path);
if (!isset($this->nodes[$method]['/'])) {
$this->nodes[$method]['/'] = $this->NodeInstance('/', 0, $method);
}
$parent = $this->nodes[$method]['/'];
if (!empty($explode)) {
$parent = $this->bindNode($parent, $explode, $method);
}
return $parent->setHandler($handler, $path);
}
/**
* @param Node $parent
* @param array $explode
* @param $method
* @return Node
* @throws Exception
*/
private function bindNode(Node $parent, array $explode, $method): Node
{
$a = 0;
foreach ($explode as $value) {
++$a;
$search = $parent->findNode($value);
if ($search === null) {
$parent = $parent->addChild($this->NodeInstance($value, $a, $method));
} else {
$parent = $search;
}
}
return $parent;
}
/**
* @param $route
* @param $handler
* @return Node|null
* @throws
*/
public function socket($route, $handler): ?Node
{
return $this->addRoute($route, $handler, 'socket');
}
/**
* @param $route
* @param $handler
* @return Node|null
* @throws
*/
public function post($route, $handler): ?Node
{
return $this->addRoute($route, $handler, 'POST');
}
/**
* @param $route
* @param $handler
* @return Node|null
* @throws
*/
public function get($route, $handler): ?Node
{
return $this->addRoute($route, $handler, 'GET');
}
/**
* @param $port
* @param callable $callback
* @return mixed
* @throws
*/
public function addRpcService($port, callable $callback): mixed
{
return call_user_func($callback, new Actuator($port));
}
/**
* @param $route
* @param $handler
* @return Node|null
* @throws
*/
public function options($route, $handler): ?Node
{
return $this->addRoute($route, $handler, 'OPTIONS');
}
/**
* @param $route
* @param $handler
* @return Any
* @throws
*/
public function any($route, $handler): Any
{
$nodes = [];
foreach ($this->methods as $method) {
$nodes[] = $this->addRoute($route, $handler, $method);
}
return new Any($nodes);
}
/**
* @param $route
* @param $handler
* @return Node|null
* @throws
*/
public function delete($route, $handler): ?Node
{
return $this->addRoute($route, $handler, 'DELETE');
}
/**
* @param $route
* @param $handler
* @return Node|null
* @throws Exception
*/
public function head($route, $handler): ?Node
{
return $this->addRoute($route, $handler, 'HEAD');
}
/**
* @param $route
* @param $handler
* @return Node|null
* @throws
*/
public function put($route, $handler): ?Node
{
return $this->addRoute($route, $handler, 'PUT');
}
/**
* @param $value
* @param int $index
* @param string $method
* @return Node
* @throws
*/
public function NodeInstance($value, int $index = 0, string $method = 'GET'): Node
{
$node = new Node();
$node->childes = [];
$node->path = $value;
$node->index = $index;
$node->method = $method;
$node->namespace = $this->loadNamespace($method);
$name = array_column($this->groupTacks, 'middleware');
if ($this->middleware instanceof \Closure) {
$node->addMiddleware([$this->middleware]);
}
if (is_array($name)) {
$node->addMiddleware($this->resolve_middleware($name));
}
return $node;
}
/**
* @param string|array $middleware
* @return array
* @throws NotFindClassException
* @throws ReflectionException
*/
private function resolve_middleware(string|array $middleware): array
{
if (is_string($middleware)) {
$middleware = [$middleware];
}
$array = [];
foreach ($middleware as $value) {
if (is_array($value)) {
foreach ($value as $item) {
$array[] = $this->getMiddlewareInstance($item);
}
} else {
$array[] = $this->getMiddlewareInstance($value);
}
}
return array_filter($array);
}
/**
* @param $value
* @return Closure|array|null
* @throws NotFindClassException
* @throws ReflectionException
*/
private function getMiddlewareInstance($value): null|Closure|array
{
if (!is_string($value)) {
return $value;
}
$value = Kiri::createObject($value);
if (!($value instanceof Middleware)) {
return null;
}
return [$value, 'onHandler'];
}
/**
* @param $method
* @return array
*/
private function loadNamespace($method): array
{
$name = array_column($this->groupTacks, 'namespace');
array_unshift($name, $this->dir);
return array_filter($name);
}
/**
* @param array $config
* @param callable $callback
* 路由分组
* @param null $stdClass
*/
public function group(array $config, callable $callback, $stdClass = null)
{
$this->groupTacks[] = $config;
if ($stdClass) {
$callback($stdClass);
} else {
$callback($this);
}
array_pop($this->groupTacks);
}
/**
* @return string
*/
public function addPrefix(): string
{
$prefix = array_column($this->groupTacks, 'prefix');
$prefix = array_filter($prefix);
if (empty($prefix)) {
return '';
}
return '/' . implode('/', $prefix);
}
/**
* @param array|null $explode
* @param $method
* @return Node|null
* 查找指定路由
*/
public function tree_search(?array $explode, $method): ?Node
{
if (!isset($this->nodes[$method])) {
return null;
}
$parent = $this->nodes[$method]['/'];
while ($value = array_shift($explode)) {
$node = $parent->findNode($value);
if (!$node) {
return null;
}
$parent = $node;
}
return $parent;
}
/**
* @param $path
* @return array|null
*/
public function split($path): ?array
{
$path = $this->addPrefix() . '/' . ltrim($path, '/');
if ($path === '/') {
return [];
}
$filter = array_filter(explode('/', $path));
if (!empty($filter)) {
return $filter;
}
return [];
}
/**
* @return array
*/
public function each(): array
{
$paths = [];
foreach ($this->nodes as $node) {
/** @var Node[] $node */
foreach ($node as $path => $_node) {
$paths[] = strtoupper($_node->method) . ' : ' . $path;
}
}
return $paths;
}
/**
* @param $exception
* @return mixed
* @throws Exception
*/
public function exception($exception): mixed
{
return Kiri::app()->getLogger()->exception($exception);
}
/**
* @param Request $request
* @return Node|null 树干搜索
* 树干搜索
* @throws Exception
*/
public function find_path(Request $request): ?Node
{
$method = $request->getMethod();
$methods = $this->nodes[$method][\request()->getUri()] ?? null;
if (!is_null($methods)) {
return $methods;
}
if ($request->isOption) {
return $this->nodes[$method]['*'] ?? null;
}
return null;
}
/**
* @param $uri
* @param $method
* @return Node|null
*/
public function search($uri, $method): Node|null
{
if (!isset($this->nodes[$method])) {
return null;
}
$methods = $this->nodes[$method];
if (isset($methods[$uri])) {
return $methods[$uri];
}
return $methods['/'] ?? null;
}
/**
* @param $request
* @return Node|null
*/
private function search_options($request): ?Node
{
$method = $request->getMethod();
if (!isset($this->nodes[$method])) {
return null;
}
if (!isset($this->nodes[$method]['*'])) {
return null;
}
return $this->nodes[$method]['*'];
}
/**
* @param RequestInterface $request
* @return Node|null
* 树杈搜索
*/
public function Branch_search(RequestInterface $request): ?Node
{
$node = $this->tree_search($request->getExplode(), $request->getMethod());
if ($node instanceof Node) {
return $node;
}
if (!$request->isOption) {
return null;
}
$node = $this->tree_search(['*'], $request->getMethod());
if (!($node instanceof Node)) {
return null;
}
return $node;
}
/**
* @throws
*/
public function _loader()
{
$this->loadRouteDir(APP_PATH . 'routes');
// $classes = Kiri::getAnnotation()->runtime(CONTROLLER_PATH);
//
// $di = Kiri::getDi();
// foreach ($classes as $class) {
// $methods = $di->getMethodAttribute($class);
// foreach ($methods as $method => $attribute) {
// if (empty($attribute)) {
// continue;
// }
// foreach ($attribute as $item) {
// $item->execute($class, $method);
// }
// }
// }
}
/**
* @param $path
* @throws 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);
}
}
}
}