This commit is contained in:
2021-10-25 18:25:14 +08:00
parent 6605aae410
commit a9d106a1cf
48 changed files with 5090 additions and 0 deletions
@@ -0,0 +1,13 @@
<?php
declare(strict_types=1);
namespace Http\Handler\Abstracts;
use Swoole\Coroutine;
abstract class BaseContext
{
protected static array $pool = [];
}
+110
View File
@@ -0,0 +1,110 @@
<?php
namespace Http\Handler\Abstracts;
use Annotation\Inject;
use Exception;
use Http\Handler\Handler as CHl;
use Http\Message\ServerRequest;
use Kiri\Core\Help;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
abstract class Handler implements RequestHandlerInterface
{
protected int $offset = 0;
/**
* @param CHl $handler
* @param array|null $middlewares
*/
public function __construct(public CHl $handler, public ?array $middlewares)
{
}
/**
* @param ServerRequestInterface $request
* @return ResponseInterface
* @throws Exception
*/
protected function execute(ServerRequestInterface $request): ResponseInterface
{
if (empty($this->middlewares) || !isset($this->middlewares[$this->offset])) {
return $this->dispatcher($request);
}
$middleware = $this->middlewares[$this->offset];
if (!($middleware instanceof MiddlewareInterface)) {
throw new Exception('get_implements_class($middleware) not found method process.');
}
$this->offset++;
return $middleware->process($request, $this);
}
/**
* @param ServerRequestInterface $request
* @return mixed
* @throws Exception
*/
public function dispatcher(ServerRequestInterface $request): mixed
{
$response = call_user_func($this->handler->callback, ...$this->handler->params);
if (!($response instanceof ResponseInterface)) {
$response = $this->transferToResponse($response);
}
$response->withHeader('Run-Time', $this->_runTime($request));
return $response;
}
/**
* @param ServerRequest $request
* @return float
*/
private function _runTime(ServerRequestInterface $request): float
{
$float = microtime(true) - time();
$serverParams = $request->getServerParams();
$rTime = $serverParams['request_time_float'] - $serverParams['request_time'];
return round($float - $rTime, 6);
}
/**
* @param mixed $responseData
* @return \Server\Constrict\ResponseInterface
* @throws Exception
*/
private function transferToResponse(mixed $responseData): ResponseInterface
{
$interface = response()->withStatus(200);
if (!$interface->hasContentType()) {
$interface->withContentType('application/json;charset=utf-8');
}
if (str_contains($interface->getContentType(), 'xml')) {
if (is_object($responseData)) {
$responseData = get_object_vars($responseData);
}
$interface->getBody()->write(Help::toXml($responseData));
} else if (is_array($responseData)) {
$interface->getBody()->write(json_encode($responseData));
} else {
$interface->getBody()->write((string)$responseData);
}
return $interface;
}
}
@@ -0,0 +1,70 @@
<?php
namespace Http\Handler\Abstracts;
use Closure;
class HandlerManager
{
private static array $handlers = [];
/**
* @param string $path
* @param string $method
* @param \Http\Handler\Handler|Closure $handler
*/
public static function add(string $path, string $method, \Http\Handler\Handler|Closure $handler)
{
if (!isset(static::$handlers[$path])) {
static::$handlers[$path] = [];
}
static::$handlers[$path][$method] = $handler;
}
/**
* @param $path
* @param $method
* @return null|int|array|Closure
*/
public static function get($path, $method): null|int|\Http\Handler\Handler|Closure
{
if (!isset(static::$handlers[$path])) {
return null;
}
$array = static::$handlers[$path][$method] ?? null;
if (is_null($array)) {
return 405;
}
return $array;
}
/**
* @return array
*/
public static function getHandlers(): array
{
return static::$handlers;
}
/**
* @return array
*/
public static function dump(): array
{
$array = [];
foreach (static::$handlers as $path => $handlers) {
$array[] = [
'path' => $path,
'method' => implode(',', array_keys($handlers))
];
}
return $array;
}
}
@@ -0,0 +1,52 @@
<?php
declare(strict_types=1);
namespace Http\Handler\Abstracts;
use Exception;
use Kiri\Abstracts\Component;
use Kiri\Kiri;
/**
* Class HttpService
* @package Http\Abstracts
*/
abstract class HttpService extends Component
{
/**
* @param $message
* @param string $category
* @throws Exception
*/
protected function write($message, string $category = 'app')
{
$logger = Kiri::app()->getLogger();
$logger->write($message, $category);
}
/**
* @param $name
* @return mixed
* @throws Exception
*/
public function __get($name): mixed
{
if (method_exists($this, $name)) {
return $this->{$name}();
}
$handler = 'get' . ucfirst($name);
if (method_exists($this, $handler)) {
return $this->{$handler}();
}
if (property_exists($this, $name)) {
return $this->$name;
}
$message = sprintf('method %s::%s not exists.', static::class, $name);
throw new Exception($message);
}
}
@@ -0,0 +1,20 @@
<?php
namespace Http\Handler\Abstracts;
use Annotation\Inject;
use Psr\Http\Server\MiddlewareInterface;
use Http\Constrict\ResponseInterface;
/**
*
*/
abstract class Middleware implements MiddlewareInterface
{
#[Inject(ResponseInterface::class)]
public ResponseInterface $response;
}
@@ -0,0 +1,86 @@
<?php
namespace Http\Handler\Abstracts;
use Closure;
use Co\Iterator;
use Kiri\Abstracts\BaseObject;
/**
* Class MiddlewareManager
* @package Http\Route
*/
class MiddlewareManager extends BaseObject
{
/**
* @var array<string, Iterator>
*/
private static array $_middlewares = [];
/**
* @param $class
* @param $method
* @param array|string|null $middlewares
* @return bool
*/
public static function add($class, $method, array|string|null $middlewares): bool
{
[$class, $method] = static::setDefault($class, $method);
if (empty($middlewares)) {
return false;
}
if (is_string($middlewares)) {
$middlewares = [$middlewares];
}
$source = &static::$_middlewares[$class][$method];
foreach ($middlewares as $middleware) {
$middleware = di($middleware);
if (in_array($middleware, $source)) {
continue;
}
$source[] = $middleware;
}
return true;
}
/**
* @param $class
* @param $method
* @return array
*/
private static function setDefault($class, $method): array
{
if (is_object($class)) {
$class = $class::class;
}
if (!isset(static::$_middlewares[$class])) {
static::$_middlewares[$class] = [];
}
if (!isset(static::$_middlewares[$class][$method])) {
static::$_middlewares[$class][$method] = [];
}
return [$class, $method];
}
/**
* @param $handler
* @return Iterator|null
*/
public static function get($handler): ?array
{
if (!($handler instanceof Closure)) {
return static::$_middlewares[$handler[0]][$handler[1]] ?? null;
}
return null;
}
}
@@ -0,0 +1,9 @@
<?php
namespace Http\Handler\Annotation;
use Annotation\Attribute;
#[\Attribute(\Attribute::TARGET_CLASS)] class ControllerTarget extends Attribute
{
}
+25
View File
@@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
namespace Http\Handler;
/**
* Interface AuthIdentity
* @package Kiri\Kiri\Http
*/
interface AuthIdentity
{
public function getIdentity();
/**
* @return string|int
* 获取唯一识别码
*/
public function getUniqueId(): string|int;
}
+189
View File
@@ -0,0 +1,189 @@
<?php
namespace Http\Handler;
use Http\Handler\Abstracts\BaseContext;
use Swoole\Coroutine;
/**
* Class Context
* @package Yoc\http
*/
class Context extends BaseContext
{
protected static array $_contents = [];
/**
* @param $id
* @param $context
* @param null $coroutineId
* @return mixed
*/
public static function setContext($id, $context, $coroutineId = null): mixed
{
if (Coroutine::getCid() === -1) {
return static::$_contents[$id] = $context;
}
return Coroutine::getContext($coroutineId)[$id] = $context;
}
/**
* @param $id
* @param int $value
* @param null $coroutineId
* @return bool|int
*/
public static function increment($id, int $value = 1, $coroutineId = null): bool|int
{
if (!isset(Coroutine::getContext($coroutineId)[$id])) {
Coroutine::getContext($coroutineId)[$id] = 0;
}
return Coroutine::getContext($coroutineId)[$id] += $value;
}
/**
* @param $id
* @param int $value
* @param null $coroutineId
* @return bool|int
*/
public static function decrement($id, int $value = 1, $coroutineId = null): bool|int
{
if (!isset(Coroutine::getContext($coroutineId)[$id])) {
Coroutine::getContext($coroutineId)[$id] = 0;
}
return Coroutine::getContext($coroutineId)[$id] -= $value;
}
/**
* @param $id
* @param null $default
* @param null $coroutineId
* @return mixed
*/
public static function getContext($id, $default = null, $coroutineId = null): mixed
{
if (Coroutine::getCid() === -1) {
return static::loadByStatic($id, $default);
}
return static::loadByContext($id, $default, $coroutineId);
}
/**
* @param $id
* @param null $default
* @param null $coroutineId
* @return mixed
*/
private static function loadByContext($id, $default = null, $coroutineId = null): mixed
{
return Coroutine::getContext($coroutineId)[$id] ?? $default;
}
/**
* @param $id
* @param null $default
* @return mixed
*/
private static function loadByStatic($id, $default = null): mixed
{
return static::$_contents[$id] ?? $default;
}
/**
* @param null $coroutineId
* @return mixed
*/
public static function getAllContext($coroutineId = null): mixed
{
if (Coroutine::getCid() === -1) {
return Coroutine::getContext($coroutineId) ?? [];
} else {
return static::$_contents ?? [];
}
}
/**
* @param string $id
* @param null $coroutineId
*/
public static function remove(string $id, $coroutineId = null)
{
if (!static::hasContext($id, $coroutineId)) {
return;
}
if (Coroutine::getCid() === -1) {
unset(static::$_contents[$id]);
} else {
unset(Coroutine::getContext($coroutineId)[$id]);
}
}
/**
* @param $id
* @param null $key
* @param null $coroutineId
* @return bool
*/
public static function hasContext($id, $key = null, $coroutineId = null): bool
{
if (Coroutine::getCid() === -1) {
return static::searchByStatic($id, $key);
}
return static::searchByCoroutine($id, $key, $coroutineId);
}
/**
* @param $id
* @param null $key
* @return bool
*/
private static function searchByStatic($id, $key = null): bool
{
if (!isset(static::$_contents[$id])) {
return false;
}
if (!empty($key) && !isset(static::$_contents[$id][$key])) {
return false;
}
return true;
}
/**
* @param $id
* @param null $key
* @param null $coroutineId
* @return bool
*/
private static function searchByCoroutine($id, $key = null, $coroutineId = null): bool
{
if (!isset(Coroutine::getContext($coroutineId)[$id])) {
return false;
}
if ($key !== null) {
return isset((Coroutine::getContext($coroutineId)[$id] ?? [])[$key]);
}
return true;
}
/**
* @return bool
*/
public static function inCoroutine(): bool
{
return Coroutine::getCid() !== -1;
}
}
+59
View File
@@ -0,0 +1,59 @@
<?php
declare(strict_types=1);
namespace Http\Handler;
use Annotation\Inject;
use Kiri\Di\ContainerInterface;
use Psr\Log\LoggerInterface;
use Http\Constrict\RequestInterface;
use Http\Constrict\ResponseInterface;
/**
* Class WebController
* @package Kiri\Kiri\Web
*/
class Controller
{
/**
* inject di container
*
* @var ContainerInterface|null
*/
#[Inject(ContainerInterface::class)]
public ?ContainerInterface $container = null;
/**
* inject request
*
* @var RequestInterface|null
*/
#[Inject(RequestInterface::class)]
public ?RequestInterface $request = null;
/**
* inject response
*
* @var ResponseInterface|null
*/
#[Inject(ResponseInterface::class)]
public ?ResponseInterface $response = null;
/**
* inject logger
*
* @var LoggerInterface
*/
#[Inject(LoggerInterface::class)]
public LoggerInterface $logger;
}
+41
View File
@@ -0,0 +1,41 @@
<?php
namespace Http\Handler;
use Exception;
use Http\Handler\Abstracts\Middleware;
use Http\Message\ServerRequest;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
/**
*
*/
class CoreMiddleware extends Middleware
{
/**
* @param ServerRequest $request
* @param RequestHandlerInterface $handler
* @return ResponseInterface
* @throws Exception
*/
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$requestMethod = $request->getAccessControlRequestMethod();
$allowHeaders = $request->getAccessControlAllowHeaders();
if (empty($requestMethod)) $requestMethod = '*';
if (empty($allowHeaders)) $allowHeaders = '*';
$this->response->withAccessControlAllowOrigin('*')->withAccessControlRequestMethod($requestMethod)
->withAccessControlAllowHeaders($allowHeaders);
return $handler->handle($request);
}
}
+10
View File
@@ -0,0 +1,10 @@
<?php
namespace Http\Handler;
class DataGrip
{
}
+27
View File
@@ -0,0 +1,27 @@
<?php
namespace Http\Handler;
use Exception;
use Kiri\Core\Help;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
/**
*
*/
class Dispatcher extends \Http\Handler\Abstracts\Handler
{
/**
* @param ServerRequestInterface $request
* @return ResponseInterface
* @throws Exception
*/
public function handle(ServerRequestInterface $request): ResponseInterface
{
return $this->execute($request);
}
}
@@ -0,0 +1,50 @@
<?php
namespace Http\Handler\Formatter;
use Exception;
use Http\Handler\Abstracts\HttpService;
use Swoole\Http\Response;
/**
*
*/
class FileFormatter extends HttpService implements IFormatter
{
public mixed $data;
/** @var Response */
public Response $status;
public array $header = [];
/**
* @param $context
* @return $this
* @throws Exception
*/
public function send($context): static
{
$this->data = $context;
return $this;
}
/**
* @return mixed
*/
public function getData(): mixed
{
$data = $this->data;
$this->clear();
return $data;
}
public function clear(): void
{
$this->data = null;
unset($this->data);
}
}
@@ -0,0 +1,61 @@
<?php
/**
* Created by PhpStorm.
* User: whwyy
* Date: 2018/4/8 0008
* Time: 17:51
*/
declare(strict_types=1);
namespace Http\Handler\Formatter;
use Exception;
use Http\Handler\Abstracts\HttpService;
use Kiri\Core\Json;
use Swoole\Http\Response;
/**
* Class HtmlFormatter
* @package Kiri\Kiri\Http\Formatter
*/
class HtmlFormatter extends HttpService implements IFormatter
{
public mixed $data;
/** @var Response */
public Response $status;
public array $header = [];
/**
* @param $context
* @return $this
* @throws Exception
*/
public function send($context): static
{
if (!is_string($context)) {
$context = Json::encode($context);
}
$this->data = $context;
return $this;
}
/**
* @return mixed
*/
public function getData(): mixed
{
$data = $this->data;
$this->clear();
return $data;
}
public function clear(): void
{
$this->data = null;
unset($this->data);
}
}
@@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
/**
* Created by PhpStorm.
* User: whwyy
* Date: 2018/4/8 0008
* Time: 17:29
*/
namespace Http\Handler\Formatter;
/**
* Interface IFormatter
* @package Kiri\Kiri\Http\Formatter
*/
interface IFormatter
{
/**
* @param $context
* @return static
*/
public function send($context): static;
/**
* @return mixed
*/
public function getData(): mixed;
public function clear(): void;
}
@@ -0,0 +1,55 @@
<?php
/**
* Created by PhpStorm.
* User: whwyy
* Date: 2018/4/8 0008
* Time: 17:18
*/
declare(strict_types=1);
namespace Http\Handler\Formatter;
use Http\Handler\Abstracts\HttpService;
/**
* Class JsonFormatter
* @package Kiri\Kiri\Http\Formatter
*/
class JsonFormatter extends HttpService implements IFormatter
{
public mixed $data;
public int $status = 200;
public array $header = [];
/**
* @param $context
* @return JsonFormatter
*/
public function send($context): static
{
if (!is_string($context)) {
$context = json_encode($context);
}
$this->data = $context;
return $this;
}
/**
* @return mixed
*/
public function getData(): mixed
{
$data = $this->data;
$this->clear();
return $data;
}
public function clear(): void
{
$this->data = null;
unset($this->data);
}
}
@@ -0,0 +1,89 @@
<?php
/**
* Created by PhpStorm.
* User: whwyy
* Date: 2018/4/8 0008
* Time: 17:29
*/
declare(strict_types=1);
namespace Http\Handler\Formatter;
use Exception;
use Http\Handler\Abstracts\HttpService;
use SimpleXMLElement;
use Swoole\Http\Response;
/**
* Class XmlFormatter
* @package Kiri\Kiri\Http\Formatter
*/
class XmlFormatter extends HttpService implements IFormatter
{
public ?string $data = '';
/** @var Response */
public Response $status;
public array $header = [];
/**
* @param $context
* @return $this
* @throws Exception
*/
public function send($context): static
{
if (!is_string($context)) {
// TODO: Implement send() method.
$dom = new SimpleXMLElement('<xml/>');
$this->toXml($dom, $context);
$this->data = $dom->saveXML();
}
return $this;
}
/**
* @return string|null
*/
public function getData(): ?string
{
$data = $this->data;
$this->clear();
return $data;
}
/**
* @param SimpleXMLElement $dom
* @param $data
*/
public function toXml(SimpleXMLElement $dom, $data)
{
foreach ($data as $key => $val) {
if (is_numeric($key)) {
$key = 'item' . $key;
}
if (is_array($val)) {
$node = $dom->addChild($key);
$this->toXml($node, $val);
} else if (is_object($val)) {
$val = get_object_vars($val);
$node = $dom->addChild($key);
$this->toXml($node, $val);
} else {
$dom->addChild($key, htmlspecialchars((string)$val));
}
}
}
public function clear(): void
{
$this->data = null;
unset($this->data);
}
}
+94
View File
@@ -0,0 +1,94 @@
<?php
namespace Http\Handler;
use Annotation\Aspect;
use Closure;
use Http\Handler\Abstracts\MiddlewareManager;
use Kiri\Di\NoteManager;
use Kiri\Events\EventProvider;
use Kiri\Kiri;
use Server\Events\OnAfterWorkerStart;
class Handler
{
public string $route = '';
public array|Closure|null $callback;
public ?array $params = [];
public ?array $_middlewares = [];
/**
* @param string $route
* @param array|Closure $callback
* @throws \ReflectionException
*/
public function __construct(string $route, array|Closure $callback)
{
$this->route = $route;
$this->_injectParams($callback);
$this->callback = $callback;
$dispatcher = Kiri::getDi()->get(EventProvider::class);
$dispatcher->on(OnAfterWorkerStart::class, function () {
if ($this->callback instanceof Closure) {
return;
}
$this->_middlewares = MiddlewareManager::get($this->callback);
$aspect = NoteManager::getSpecify_annotation(Aspect::class, $this->callback[0], $this->callback[1]);
$this->callback[0] = Kiri::getDi()->get($this->callback[0]);
if (!is_null($aspect)) {
$this->recover($aspect);
}
});
}
/**
* @param Aspect $aspect
*/
public function recover(Aspect $aspect)
{
$aspect = Kiri::getDi()->get($aspect->aspect);
if (empty($aspect)) {
return;
}
$callback = $this->callback;
$params = $this->params;
$this->params = [];
$this->callback = static function () use ($aspect, $callback, $params) {
$aspect->before();
$result = $aspect->invoke($callback, $params);
$aspect->after($result);
return $result;
};
}
/**
* @param array|Closure $callback
* @throws \ReflectionException
*/
private function _injectParams(array|Closure $callback)
{
$container = Kiri::getDi();
if (!($callback instanceof Closure)) {
$this->params = $container->getMethodParameters($callback[0], $callback[1]);
} else {
$this->params = $container->getFunctionParameters($callback);
}
}
}
+179
View File
@@ -0,0 +1,179 @@
<?php
namespace Http\Handler;
use Annotation\Aspect;
use Closure;
use Exception;
use Psr\Http\Server\MiddlewareInterface;
use Kiri\Di\NoteManager;
use Kiri\IAspect;
use Kiri\Kiri;
use ReflectionException;
use Throwable;
class Pipeline
{
protected mixed $passable;
protected mixed $overall;
protected mixed $pipes = [];
protected mixed $pipeline;
protected mixed $exceptionHandler;
/**
* 初始数据
* @param $passable
* @return $this
*/
public function send($passable): static
{
$this->passable = $passable;
return $this;
}
/**
* @param $middle
* @return $this
*/
public function overall($middle): static
{
$this->overall = $middle;
return $this;
}
/**
* 调用栈
* @param $pipes
* @return $this
*/
public function through($pipes): static
{
if (empty($pipes)) return $this;
if (empty($this->pipes)) {
$this->pipes = is_array($pipes) ? $pipes : func_get_args();
} else {
foreach ($pipes as $pipe) {
$this->pipes[] = $pipe;
}
}
return $this;
}
/**
* 执行
* @param callable $destination
* @return static
*/
public function then(callable $destination): static
{
$parameters = $this->passable;
if (!empty($this->overall)) {
array_unshift($this->pipes, $this->overall);
}
if (is_array($destination)) {
$destination = $this->aspect_caller($destination, $parameters);
}
$this->pipeline = array_reduce(array_reverse($this->pipes), $this->carry(),
static function () use ($destination, $parameters) {
return call_user_func($destination, ...$parameters);
}
);
return $this->clear();
}
/**
* @return $this
*/
private function clear(): static
{
$this->pipes = [];
$this->passable = null;
$this->overall = null;
return $this;
}
/**
* @param $destination
* @param $parameters
* @return Closure|array
*/
private function aspect_caller($destination, $parameters): Closure|array
{
[$controller, $action] = $destination;
/** @var Aspect $aop */
$aop = NoteManager::getSpecify_annotation(Aspect::class, $controller::class, $action);
if (!empty($aop)) {
$aop = Kiri::getDi()->get($aop->aspect);
$destination = static function () use ($aop, $destination, $parameters) {
/** @var IAspect $aop */
$aop->before();
$aop->after($data = $aop->invoke($destination, $parameters));
return $data;
};
}
return $destination;
}
/**
* @param $request
* @return mixed
*/
public function interpreter($request): mixed
{
return call_user_func($this->pipeline, $request);
}
/**
* 设置异常处理器
* @param callable $handler
* @return $this
*/
public function whenException(callable $handler): static
{
$this->exceptionHandler = $handler;
return $this;
}
/**
* @return Closure
*/
protected function carry(): Closure
{
return static function ($stack, $pipe) {
return static function ($passable) use ($stack, $pipe) {
if ($pipe instanceof MiddlewareInterface) {
$pipe = [$pipe, 'process'];
}
return $pipe($passable, $stack);
};
};
}
/**
* 异常处理
* @param $passable
* @param Throwable $e
* @return mixed
* @throws Throwable
*/
protected function handleException($passable, Throwable $e): mixed
{
if ($this->exceptionHandler) {
return call_user_func($this->exceptionHandler, $passable, $e);
}
throw $e;
}
}
+263
View File
@@ -0,0 +1,263 @@
<?php
namespace Http\Handler;
use Closure;
use Exception;
use Http\Handler\Abstracts\HandlerManager;
use Http\Handler\Abstracts\MiddlewareManager;
use Kiri\Abstracts\Logger;
use Kiri\Kiri;
use Throwable;
class Router
{
protected array $groupTack = [];
protected array $methods = ['GET', 'POST', 'HEAD', 'OPTIONS', 'PUT', 'DELETE'];
/**
* @param $route
* @param $handler
* @return void
* @throws
*/
public static function socket($route, $handler): void
{
$router = Kiri::getDi()->get(Router::class);
$router->addRoute('SOCKET', $route, $handler);
}
/**
* @param $route
* @param $handler
* @return void
* @throws
*/
public static function post($route, $handler): void
{
$router = Kiri::getDi()->get(Router::class);
$router->addRoute('POST', $route, $handler);
}
/**
* @param $route
* @param $handler
* @return void
* @throws
*/
public static function get($route, $handler): void
{
$router = Kiri::getDi()->get(Router::class);
$router->addRoute('GET', $route, $handler);
}
/**
* @param $route
* @param $handler
* @return void
* @throws
*/
public static function options($route, $handler): void
{
$router = Kiri::getDi()->get(Router::class);
$router->addRoute('OPTIONS', $route, $handler);
}
/**
* @param $route
* @param $handler
* @throws
*/
public static function any($route, $handler): void
{
$router = Kiri::getDi()->get(Router::class);
foreach ($router->methods as $method) {
$router->addRoute($method, $route, $handler);
}
}
/**
* @param $route
* @param $handler
* @return void
* @throws
*/
public static function delete($route, $handler): void
{
$router = Kiri::getDi()->get(Router::class);
$router->addRoute('DELETE', $route, $handler);
}
/**
* @param $route
* @param $handler
* @return void
* @throws Exception
*/
public static function head($route, $handler): void
{
$router = Kiri::getDi()->get(Router::class);
$router->addRoute('HEAD', $route, $handler);
}
/**
* @param $route
* @param $handler
* @return void
* @throws
*/
public static function put($route, $handler): void
{
$router = Kiri::getDi()->get(Router::class);
$router->addRoute('PUT', $route, $handler);
}
/**
* @param string|array $method
* @param string $route
* @param string|Closure $closure
* @throws \ReflectionException
*/
public function addRoute(string|array $method, string $route, string|Closure $closure)
{
if (!is_array($method)) $method = [$method];
$route = $this->getPath($route);
if (is_string($closure)) {
$closure = explode('@', $closure);
$closure[0] = $this->addNamespace($closure[0]);
if (!class_exists($closure[0])) {
return;
}
$this->addMiddlewares(...$closure);
}
foreach ($method as $value) {
HandlerManager::add($route, $value, new Handler($route, $closure));
}
}
/**
* @param array $config
* @param Closure $closure
*/
public static function group(array $config, Closure $closure)
{
$router = Kiri::getDi()->get(Router::class);
array_push($router->groupTack, $config);
call_user_func($closure, $router);
array_pop($router->groupTack);
}
/**
* @param string $route
* @return string
*/
protected function getPath(string $route): string
{
$route = ltrim($route, '/');
$prefix = array_column($this->groupTack, 'prefix');
if (empty($prefix = array_filter($prefix))) {
return '/' . $route;
}
return '/' . implode('/', $prefix) . '/' . $route;
}
/**
* @param $controller
* @param $method
*/
protected function addMiddlewares($controller, $method)
{
$middleware = array_column($this->groupTack, 'middleware');
if (empty($middleware = array_filter($middleware))) {
return;
}
foreach ($middleware as $value) {
MiddlewareManager::add($controller, $method, $value);
}
}
/**
* @param $class
* @return string|null
*/
protected function addNamespace($class): ?string
{
$middleware = array_column($this->groupTack, 'namespace');
if (empty($middleware = array_filter($middleware))) {
return $class;
}
$middleware[] = $class;
return implode('\\', array_map(function ($value) {
return trim($value, '\\');
}, $middleware));
}
/**
* @throws Exception
*/
public function read_files()
{
$this->loadRouteDir(APP_PATH . 'routes');
}
/**
* @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 {
include_once "Router.php";
} catch (Throwable $exception) {
di(Logger::class)->error('router', [
$exception->getMessage(),
$exception->getFile(),
$exception->getLine(),
]);
} finally {
if (isset($exception)) {
unset($exception);
}
}
}
}