diff --git a/core/Abstracts/BaseApplication.php b/core/Abstracts/BaseApplication.php index b2c876d3..3a1d3328 100644 --- a/core/Abstracts/BaseApplication.php +++ b/core/Abstracts/BaseApplication.php @@ -13,7 +13,7 @@ namespace Kiri\Abstracts; use Annotation\Annotation as SAnnotation; use Database\Connection; use Exception; -use Http\Route\Router; +use Http\Handler\Router; use Server\Server; use Kafka\KafkaProvider; use Kiri\AspectManager; diff --git a/core/Abstracts/BaseGoto.php b/core/Abstracts/BaseGoto.php index 22504e31..35152887 100644 --- a/core/Abstracts/BaseGoto.php +++ b/core/Abstracts/BaseGoto.php @@ -5,7 +5,6 @@ namespace Kiri\Abstracts; use Exception; -use Http\Exception\ExitException; use Kiri\Core\Json; /** @@ -19,11 +18,11 @@ class BaseGoto extends Component * @param string $message * @param int $statusCode * @return mixed - * @throws ExitException + * @throws Exception */ - public function end(string $message, $statusCode = 200): mixed + public function end(string $message, int $statusCode = 200): mixed { - throw new ExitException(Json::to(12350, $message), $statusCode); + throw new Exception(Json::to(12350, $message), $statusCode); } } diff --git a/core/Abstracts/TraitApplication.php b/core/Abstracts/TraitApplication.php index fcf6caf8..bd2ed99e 100644 --- a/core/Abstracts/TraitApplication.php +++ b/core/Abstracts/TraitApplication.php @@ -9,7 +9,7 @@ use Database\Connection; use Database\DatabasesProviders; use Http\Client\Client; use Http\Client\Curl; -use Http\Route\Router; +use Http\Handler\Router; use Server\Server; use Kiri\Crontab\Producer; use Kiri\Async; diff --git a/core/Async.php b/core/Async.php index 05466eac..c11188b3 100644 --- a/core/Async.php +++ b/core/Async.php @@ -5,11 +5,8 @@ namespace Kiri; use Exception; -use Http\IInterface\Task; -use ReflectionException; use Kiri\Abstracts\Component; use Server\ServerManager; -use Server\SInterface\TaskExecute; /** * Class Async diff --git a/core/Cache/Base/Redis.php b/core/Cache/Base/Redis.php index 1494aa9f..02659959 100644 --- a/core/Cache/Base/Redis.php +++ b/core/Cache/Base/Redis.php @@ -2,7 +2,7 @@ namespace Kiri\Cache\Base; -use Http\Context\Context; +use Http\Handler\Context; use Kiri\Abstracts\Logger; use Kiri\Events\EventProvider; use Kiri\Exception\RedisConnectException; diff --git a/core/Jwt/JWTAuthMiddleware.php b/core/Jwt/JWTAuthMiddleware.php index a8437b10..733e56a0 100644 --- a/core/Jwt/JWTAuthMiddleware.php +++ b/core/Jwt/JWTAuthMiddleware.php @@ -5,17 +5,21 @@ declare(strict_types=1); namespace Kiri\Jwt; -use Closure; +use Annotation\Inject; use Exception; -use Http\Route\MiddlewareAbstracts; +use Http\Message\ServerRequest; use Kiri\Kiri; +use Psr\Http\Message\ServerRequestInterface; +use Psr\Http\Server\MiddlewareInterface; +use Psr\Http\Server\RequestHandlerInterface; +use Server\Constrict\ResponseInterface; /** * Class CoreMiddleware * @package Kiri\Kiri\Route * 跨域中间件 */ -class JWTAuthMiddleware extends MiddlewareAbstracts +class JWTAuthMiddleware implements MiddlewareInterface { @@ -23,27 +27,31 @@ class JWTAuthMiddleware extends MiddlewareAbstracts public int $zOrder = 0; + #[Inject(ResponseInterface::class)] + public ResponseInterface $response; + + /** - * @param RequestInterface $request - * @param Closure $next - * @return mixed + * @param ServerRequest $request + * @param RequestHandlerInterface $handler + * @return \Psr\Http\Message\ResponseInterface * @throws Exception */ - public function onHandler(RequestInterface $request, Closure $next): mixed + public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): \Psr\Http\Message\ResponseInterface { $authorization = $request->getHeaderLine('Authorization'); if (empty($authorization)) { - throw new JWTAuthTokenException('JWT voucher cannot be empty.'); + return $this->response->json(['code' => 401, 'JWT voucher cannot be empty.']); } if (!str_starts_with($authorization, 'Bearer ')) { - throw new JWTAuthTokenException('JWT Voucher Format Error.'); + return $this->response->json(['code' => 401, 'JWT Voucher Format Error.']); } $authorization = str_replace('Bearer ', '', $authorization); $jwt = Kiri::app()->getJwt(); if (!$jwt->validator($authorization)) { - throw new JWTAuthTokenException('JWT Validator fail.'); + return $this->response->json(['code' => 401, 'JWT Validator fail.']); } - return $next($request); + return $handler->handle($request); } } diff --git a/core/Pool/Connection.php b/core/Pool/Connection.php index 220ce2a3..3715777d 100644 --- a/core/Pool/Connection.php +++ b/core/Pool/Connection.php @@ -6,7 +6,7 @@ namespace Kiri\Pool; use Closure; use Database\Mysql\PDO; use Exception; -use Http\Context\Context; +use Http\Handler\Context; use Kiri\Abstracts\Component; use Kiri\Kiri; use Swoole\Error; diff --git a/core/Pool/Pool.php b/core/Pool/Pool.php index 7d42cbec..5440ff4a 100644 --- a/core/Pool/Pool.php +++ b/core/Pool/Pool.php @@ -5,7 +5,7 @@ namespace Kiri\Pool; use Exception; -use Http\Context\Context; +use Http\Handler\Context; use Kiri\Abstracts\Component; use Kiri\Abstracts\Config; use Kiri\Exception\ConfigException; diff --git a/core/Pool/Redis.php b/core/Pool/Redis.php index f698009f..55757865 100644 --- a/core/Pool/Redis.php +++ b/core/Pool/Redis.php @@ -8,7 +8,7 @@ namespace Kiri\Pool; use Annotation\Inject; use Closure; use Exception; -use Http\Context\Context; +use Http\Handler\Context; use Kiri\Abstracts\Component; use Kiri\Events\EventProvider; use Kiri\Exception\ConfigException; diff --git a/function.php b/function.php index 8afe5346..8b5944b4 100644 --- a/function.php +++ b/function.php @@ -4,8 +4,8 @@ defined('APP_PATH') or define('APP_PATH', realpath(__DIR__ . '/../../')); use Annotation\Annotation; -use Http\Context\Context; -use Http\Route\Router; +use Http\Handler\Context; +use Http\Handler\Router; use JetBrains\PhpStorm\Pure; use Kiri\Abstracts\Config; use Kiri\Application; diff --git a/http-helper/Abstracts/BaseContext.php b/http-handler/Abstracts/BaseContext.php similarity index 78% rename from http-helper/Abstracts/BaseContext.php rename to http-handler/Abstracts/BaseContext.php index 8f922389..78f00ef6 100644 --- a/http-helper/Abstracts/BaseContext.php +++ b/http-handler/Abstracts/BaseContext.php @@ -1,7 +1,7 @@ $handlers) { + $array[] = [ + 'path' => $path, + 'method' => implode(',', array_keys($handlers)) + ]; + } + return $array; + } + } diff --git a/http-helper/Abstracts/HttpService.php b/http-handler/Abstracts/HttpService.php similarity index 96% rename from http-helper/Abstracts/HttpService.php rename to http-handler/Abstracts/HttpService.php index ccf45f38..dc026ae4 100644 --- a/http-helper/Abstracts/HttpService.php +++ b/http-handler/Abstracts/HttpService.php @@ -1,7 +1,7 @@ withAccessControlAllowOrigin('*') + ->withAccessControlRequestMethod($request->getAccessControlRequestMethod()) + ->withAccessControlAllowHeaders($request->getAccessControlAllowHeaders()); return $handler->handle($request); } diff --git a/http-helper/Context/Formatter/FileFormatter.php b/http-handler/Formatter/FileFormatter.php similarity index 85% rename from http-helper/Context/Formatter/FileFormatter.php rename to http-handler/Formatter/FileFormatter.php index 92f6ed3c..b7a59678 100644 --- a/http-helper/Context/Formatter/FileFormatter.php +++ b/http-handler/Formatter/FileFormatter.php @@ -1,10 +1,9 @@ groupTack, $options); - - $this->addRoute('GET', $route, $closure); - - array_pop($this->groupTack); + $router = Kiri::getDi()->get(Router::class); + $router->addRoute($route, $handler, 'SOCKET'); } /** - * @param string $route - * @param string|Closure $closure - * @param array $options - * @throws \ReflectionException + * @param $route + * @param $handler + * @return void + * @throws */ - public function post(string $route, string|Closure $closure, array $options = []) + public static function post($route, $handler): void { - array_push($this->groupTack, $options); + $router = Kiri::getDi()->get(Router::class); + $router->addRoute($route, $handler, 'POST'); + } - $this->addRoute('POST', $route, $closure); + /** + * @param $route + * @param $handler + * @return void + * @throws + */ + public static function get($route, $handler): void + { + $router = Kiri::getDi()->get(Router::class); + $router->addRoute($route, $handler, 'GET'); + } - array_pop($this->groupTack); + + /** + * @param $route + * @param $handler + * @return void + * @throws + */ + public static function options($route, $handler): void + { + $router = Kiri::getDi()->get(Router::class); + $router->addRoute($route, $handler, 'OPTIONS'); + } + + + /** + * @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($route, $handler, $method); + } + } + + /** + * @param $route + * @param $handler + * @return void + * @throws + */ + public static function delete($route, $handler): void + { + $router = Kiri::getDi()->get(Router::class); + $router->addRoute($route, $handler, 'DELETE'); + } + + + /** + * @param $route + * @param $handler + * @return void + * @throws Exception + */ + public static function head($route, $handler): void + { + $router = Kiri::getDi()->get(Router::class); + $router->addRoute($route, $handler, 'HEAD'); + } + + + /** + * @param $route + * @param $handler + * @return void + * @throws + */ + public static function put($route, $handler): void + { + $router = Kiri::getDi()->get(Router::class); + $router->addRoute($route, $handler, 'PUT'); } @@ -129,4 +204,53 @@ class Router } + /** + * @throws Exception + */ + public function _loader() + { + $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 "$files"; + } catch (Throwable $exception) { + di(Logger::class)->error('router', [ + $exception->getMessage(), + $exception->getFile(), + $exception->getLine(), + ]); + } finally { + if (isset($exception)) { + unset($exception); + } + } + } + + } diff --git a/http-handler/TestRequest.php b/http-handler/TestRequest.php deleted file mode 100644 index 1c27a7e3..00000000 --- a/http-handler/TestRequest.php +++ /dev/null @@ -1,88 +0,0 @@ -response = new ResponseEmitter(); - } - - - /** - * @param Request $request - * @param Response $response - * @throws Exception - */ - public function onRequest(Request $request, Response $response): void - { - try { - [$PsrRequest, $PsrResponse] = $this->initRequestResponse($request); - /** @var Handler $handler */ - $handler = HandlerManager::get($request->server['request_uri'], $request->getMethod()); - if (is_integer($handler)) { - $PsrResponse->withStatus($handler)->withBody(new Stream('Allow Method[' . $request->getMethod() . '].')); - } else if (is_null($handler)) { - $PsrResponse->withStatus(404)->withBody(new Stream('Page not found.')); - } else { - $PsrResponse = $this->handler($handler, $PsrRequest); - } - } catch (\Throwable $throwable) { - $PsrResponse = \response()->withStatus($throwable->getCode()) - ->withContentType(\Http\Message\Response::CONTENT_TYPE_HTML) - ->withBody(new Stream(jTraceEx($throwable, null, true))); - } finally { - $this->response->sender($response, $PsrResponse); - } - } - - - /** - * @param Handler $handler - * @param $PsrRequest - * @return ResponseInterface - * @throws Exception - */ - protected function handler(Handler $handler, $PsrRequest): \Psr\Http\Message\ResponseInterface - { - $middlewares = MiddlewareManager::get($handler->callback); - - $dispatcher = new Dispatcher($handler, $middlewares); - - return $dispatcher->handle($PsrRequest); - } - - - /** - * @param Request $request - * @return array - * @throws Exception - */ - private function initRequestResponse(Request $request): array - { - $PsrResponse = Context::setContext(ResponseInterface::class, new \Http\Message\Response()); - - $PsrRequest = Context::setContext(RequestInterface::class, ServerRequest::createServerRequest($request)); - - return [$PsrRequest, $PsrResponse]; - } - -} diff --git a/http-helper/Exception/AuthException.php b/http-helper/Exception/AuthException.php deleted file mode 100644 index 96b3c5ae..00000000 --- a/http-helper/Exception/AuthException.php +++ /dev/null @@ -1,34 +0,0 @@ -nodes = $nodes; - } - - - /** - * @param $name - * @param $arguments - * @return $this - */ - public function __call($name, $arguments): static - { - foreach ($this->nodes as $node) { - $node->{$name}(...$arguments); - } - return $this; - } - -} diff --git a/http-helper/Route/CoreMiddleware.php b/http-helper/Route/CoreMiddleware.php deleted file mode 100644 index f3eb0cf5..00000000 --- a/http-helper/Route/CoreMiddleware.php +++ /dev/null @@ -1,40 +0,0 @@ -withAccessControlAllowOrigin('*') - ->withAccessControlRequestMethod($request->getAccessControlRequestMethod()) - ->withAccessControlAllowHeaders($request->getAccessControlAllowHeaders()); - return $handler->handle($request); - } - -} diff --git a/http-helper/Route/HandlerProviders.php b/http-helper/Route/HandlerProviders.php deleted file mode 100644 index 0914b290..00000000 --- a/http-helper/Route/HandlerProviders.php +++ /dev/null @@ -1,38 +0,0 @@ -priority; - } -} diff --git a/http-helper/Route/Node.php b/http-helper/Route/Node.php deleted file mode 100644 index 2da80023..00000000 --- a/http-helper/Route/Node.php +++ /dev/null @@ -1,319 +0,0 @@ - */ - private array $_handler = []; - - public string $htmlSuffix = '.html'; - public bool $enableHtmlSuffix = false; - - /** @var array */ - public array $namespace = []; - - /** @var array */ - 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; - } - - - /** - * @param Router $router - */ - public function __construct(public Router $router) - { - $eventDispatcher = di(EventProvider::class); - $eventDispatcher->on(OnAfterWorkerStart::class, [$this, 'setParameters']); - } - - - /** - * @param string $data - * @return mixed - */ - public function unpack(string $data): mixed - { - if ($this->_dataType == 'json') { - return json_decode($data, true); - } - if ($this->_dataType == 'serializes') { - return unserialize($data); - } - return $data; - } - - - /** - * @param string|array|Closure $handler - * @param string $method - * @param string $path - * @return Node - * @throws ReflectionException - */ - public function setHandler(string|array|Closure $handler, string $method, string $path): static - { - $this->sourcePath = '/' . ltrim($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.'; - return $this; - } - $this->_handler[$method] = [$handler, $this->resolveMethodParams($handler)]; - return $this; - } - - - /** - * @param $dispatcher - * @return array - * @throws \ReflectionException - */ - private function resolveMethodParams($dispatcher): array - { - $container = Kiri::getDi(); - if ($dispatcher instanceof Closure) { - $_injectParameters = $container->getFunctionParameters($dispatcher); - } else { - $_injectParameters = $container->getMethodParameters( - $dispatcher[0]::class, $dispatcher[1]); - } - return $_injectParameters; - } - - - /** - * @param string $handler - * @return array - */ - 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]; - } - - - /** - * @param string $method - * @param $handler - * @param $_injectParameters - * @throws ReflectionException - * @throws Exception - */ - private function injectMiddleware(string $method, $handler, $_injectParameters): void - { - $this->callback[$method] = (new Pipeline())->overall($this->router->getMiddleware()) - ->through($this->middleware[$method] ?? []) - ->through(MiddlewareManager::get($handler)) - ->send($_injectParameters) - ->then($handler); - } - - - /** - * @throws ReflectionException - */ - public function setParameters(): static - { - if (empty($this->_handler)) { - return $this; - } - foreach ($this->_handler as $method => $dispatcher) { - $this->injectMiddleware($method, ...$dispatcher); - } - $this->_handler = []; - return $this; - } - - - /** - * @return array - */ - #[Pure] protected function annotation(): array - { - return $this->getMiddleWares(); - } - - - /** - * @param RequestInterface $request - * @return bool - */ - public function methodAllow(RequestInterface $request): bool - { - if (!in_array($request->getMethod(), $this->method)) { - return true; - } - return $this->method == 'any'; - } - - /** - * @return bool - * @throws Exception - */ - public function checkSuffix(): bool - { - if ($this->enableHtmlSuffix) { - $url = request()->getUri()->getPath(); - $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->path] = $node; - return $node; - } - - - /** - * @param string $search - * @return Node|null - * @throws Exception - */ - public function findNode(string $search): ?Node - { - return $this->childes[$search] ?? 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 $method - * @param Closure|array $class - * @return $this - */ - public function addMiddleware($method, Closure|array $class): static - { - if (empty($class)) return $this; - if (!isset($this->middleware[$method])) { - $this->middleware[$method] = []; - } - foreach ($class as $closure) { - if (in_array($closure, $this->middleware[$method])) { - continue; - } - $this->middleware[$method][] = $closure; - } - return $this; - } - - - /** - * @return array - */ - public function getMiddleWares(): array - { - return $this->middleware; - } - - - /** - * @param RequestInterface $request - * @return mixed - * @throws RequestException - * @throws Exception - */ - public function dispatch(RequestInterface $request): mixed - { - if (!in_array($request->getMethod(), $this->method)) { - throw new RequestException(Constant::STATUS_405_MESSAGE, 405); - } - if (empty($this->callback[$request->getMethod()])) { - throw new RequestException(Constant::STATUS_404_MESSAGE, 404); - } - return $this->callback[$request->getMethod()]->interpreter($request); - } - -} diff --git a/http-helper/Route/Router.php b/http-helper/Route/Router.php deleted file mode 100644 index 5275461c..00000000 --- a/http-helper/Route/Router.php +++ /dev/null @@ -1,587 +0,0 @@ -middleware = $middleware; - } - - - /** - * @throws ConfigException - * @throws Exception - * 初始化函数路径 - */ - public function init() - { - $this->namespace = Config::get('http.namespace', $this->namespace); - } - - - /** - * @return mixed - * @throws ConfigException - * @throws Exception - */ - public static function getNamespace(): string - { - $router = Kiri::getDi()->get(Router::class); - - return Config::get('http.namespace', $router->namespace); - } - - - /** - * @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 - */ - public function addRoute($path, $handler, string $method = 'any'): ?Node - { - if ($handler instanceof Closure) { - $handler = Closure::bind($handler, di(Controller::class)); - } - - - $di = Kiri::getDi()->get(\Http\Handler\Router::class); - $di->addRoute($method, $path, $handler); - - - return null; - return $this->tree($path, $handler, $method); - } - - /** - * @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 - { - [$parent, $explode] = $this->getRootNode($path, $method); - - if (!empty($explode)) { - $parent = $this->bindNode($parent, $explode, $method); - } - - if (!in_array($method, $parent->method)) { - $parent->method[] = $method; - } - return $parent->setHandler($handler, $method, $path); - } - - - /** - * @param $root - * @param $method - * @param bool $create - * @return array - */ - private function getRootNode($root, $method, bool $create = true): array - { - [$start, $explode] = $this->path_recombination($root); - $parent = $this->nodes[$start] ?? null; - if ($parent instanceof Node) { - return [$parent, $explode]; - } - if ($create) { - $parent = $this->NodeInstance($root, 0, $method); - $this->nodes[$start] = $parent; - - return [$parent, $explode]; - } - return [null, null]; - } - - - /** - * @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 void - * @throws - */ - public static function socket($route, $handler): void - { - $router = Kiri::getDi()->get(Router::class); - $router->addRoute($route, $handler, 'SOCKET'); - } - - - /** - * @param $route - * @param $handler - * @return void - * @throws - */ - public static function post($route, $handler): void - { - $router = Kiri::getDi()->get(Router::class); - $router->addRoute($route, $handler, 'POST'); - } - - /** - * @param $route - * @param $handler - * @return void - * @throws - */ - public static function get($route, $handler): void - { - $router = Kiri::getDi()->get(Router::class); - $router->addRoute($route, $handler, 'GET'); - } - - - /** - * @param $route - * @param $handler - * @return void - * @throws - */ - public static function options($route, $handler): void - { - $router = Kiri::getDi()->get(Router::class); - $router->addRoute($route, $handler, 'OPTIONS'); - } - - - /** - * @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($route, $handler, $method); - } - } - - /** - * @param $route - * @param $handler - * @return void - * @throws - */ - public static function delete($route, $handler): void - { - $router = Kiri::getDi()->get(Router::class); - $router->addRoute($route, $handler, 'DELETE'); - } - - - /** - * @param $route - * @param $handler - * @return void - * @throws Exception - */ - public static function head($route, $handler): void - { - $router = Kiri::getDi()->get(Router::class); - $router->addRoute($route, $handler, 'HEAD'); - } - - - /** - * @param $route - * @param $handler - * @return void - * @throws - */ - public static function put($route, $handler): void - { - $router = Kiri::getDi()->get(Router::class); - $router->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($this); - $node->childes = []; - $node->path = $value; - $node->index = $index; - $node->method[] = $method; - $node->namespace = $this->loadNamespace(); - - $name = array_column($this->groupTacks, 'middleware'); - if (is_array($name)) { - $node->addMiddleware($method, $this->resolve_middleware($name)); - } - return $node; - } - - - /** - * @return Closure|null - */ - public function getMiddleware(): ?Closure - { - return $this->middleware; - } - - - /** - * @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 - * @throws Exception - */ - private function getMiddlewareInstance($value): null|Closure|array - { - if (!is_string($value)) { - return $value; - } - $value = Kiri::createObject($value); - if (!($value instanceof MiddlewareInterface)) { - return null; - } - return [$value, 'onHandler']; - } - - - /** - * @return array - */ - private function loadNamespace(): array - { - $name = array_column($this->groupTacks, 'namespace'); - array_unshift($name, $this->namespace); - return array_filter($name); - } - - /** - * @param array $config - * @param callable $callback - * 路由分组 - */ - public static function group(array $config, callable $callback) - { - $di = Kiri::getDi()->get(\Http\Handler\Router::class); - $di->group($config, $callback); - } - - /** - * @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 - * @return Node|null - * 查找指定路由 - * @throws Exception - */ - public function tree_search(?array $explode): ?Node - { - $start = array_shift($explode); - foreach ($this->nodes as $node) { - if ($node->path == $start) { - $parent = $node; - } - } - if (!isset($parent)) { - return null; - } - while ($value = array_shift($explode)) { - $node = $parent->findNode($value); - if (!$node) { - return null; - } - $parent = $node; - } - return $parent; - } - - /** - * @param $path - * @return array|null - */ - public function path_recombination($path): ?array - { - $path = $this->addPrefix() . '/' . ltrim($path, '/'); - if ($path === '/') { - return ['/', null]; - } - $filter = array_filter(explode('/', $path)); - if (!empty($filter)) { - return [array_shift($filter), $filter]; - } - return ['/', null]; - } - - /** - * @return array - */ - public function each(): array - { - $paths = []; - foreach ($this->nodes as $_node) { - /** @var Node[] $node */ - $paths[] = ['method' => $_node->method, 'path' => $_node->sourcePath, 'alias' => $_node->getAlias()]; - $paths = $this->getChildes($_node, $paths); - } - return $paths; - } - - - /** - * @param Node $node - * @param array $path - * @return array - */ - private function getChildes(Node $node, array $path): array - { - foreach ($node->childes as $item) { - $path[] = ['method' => $item->method, 'path' => $item->sourcePath, 'alias' => $item->getAlias()]; - if (!empty($item->childes)) { - $path = $this->getChildes($item, $path); - } - } - return $path; - } - - - /** - * @param $exception - * @return mixed - * @throws Exception - */ - public function exception($exception): mixed - { - return Kiri::app()->getLogger()->exception($exception); - } - - - /** - * @param RequestInterface $request - * @return Node|null - * 树杈搜索 - * @throws Exception - */ - public function radix_tree(RequestInterface $request): ?Node - { - $path = $request->getUri()->getPath(); - - [$parent, $explode] = $this->getRootNode($path, $request->getMethod(), false); - if ($parent && !empty($explode)) { - $parent = $this->searchNode($explode, $parent); - } - return $parent; - } - - - /** - * @param $explode - * @param $parent - * @return null|Node - * @throws Exception - */ - private function searchNode($explode, $parent): ?Node - { - /** @var Node $parent */ - foreach ($explode as $value) { - $node = $parent->findNode($value); - if (!$node) { - return null; - } - $parent = $node; - } - return $parent; - } - - - /** - * @throws - */ - public function _loader() - { - $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 "$files"; - } catch (Throwable $exception) { - $this->addError($exception, 'throwable'); - } finally { - if (isset($exception)) { - unset($exception); - } - } - } - -} diff --git a/http-helper/Shutdown.php b/http-helper/Shutdown.php deleted file mode 100644 index 5146dc7d..00000000 --- a/http-helper/Shutdown.php +++ /dev/null @@ -1,181 +0,0 @@ -taskDirectory = storage(null, 'pid/task'); - $this->workerDirectory = storage(null, 'pid/worker'); - $this->managerDirectory = storage(null, 'pid/manager'); - $this->processDirectory = storage(null, 'pid/process'); - } - - - /** - * @throws Exception - */ - public function shutdown(): void - { - clearstatcache(storage()); - $output = shell_exec('[ -f /.dockerenv ] && echo yes || echo no'); - if (trim($output) === 'yes') { - return; - } - - $server = di(ServerManager::class)->getServer(); - $master_pid = $server->setting['pid_file'] ?? PID_PATH; - if (file_exists($master_pid)) { - $this->close(file_get_contents($master_pid)); - } - $this->closeOther(); - } - - - /** - * 关闭其他进程 - */ - private function closeOther(): void - { - $this->directoryCheck($this->managerDirectory); - $this->directoryCheck($this->taskDirectory); - $this->directoryCheck($this->workerDirectory); - $this->directoryCheck($this->processDirectory); - } - - - /** - * @return bool - * @throws Exception - * check server is running. - */ - public function isRunning(): bool - { - $server = di(ServerManager::class)->getServer(); - $master_pid = $server->setting['pid_file'] ?? PID_PATH; - - if (!file_exists($master_pid)) { - return false; - } - - return $this->pidIsExists(file_get_contents($master_pid)); - } - - - /** - * @param $content - * @return bool - */ - public function pidIsExists($content): bool - { - if (intval($content) < 1) { - return false; - } - exec('ps -eo pid', $output); - $output = array_filter($output, function ($value) { - return intval($value); - }); - return in_array(intval($content), $output); - } - - - /** - * @param string $path - * @return bool - */ - public function directoryCheck(string $path): bool - { - $values = $this->getProcessPidS($path); - if (empty($values)) return false; - - $diff = array_diff($values, $this->getPidS()); - foreach ($diff as $value) { - $this->pidIsExists($value); - } - return false; - } - - - /** - * @param $path - * @return array|bool - */ - private function getProcessPidS($path): bool|array - { - $values = []; - $dir = new \DirectoryIterator($path); - if ($dir->getSize() < 1) { - return $values; - } - foreach ($dir as $value) { - if ($value->isDot()) continue; - - if (!$value->valid()) continue; - - $_value = file_get_contents($value->getRealPath()); - if (empty($_value)) { - continue; - } - $values[] = intval($_value); - - @unlink($value->getRealPath()); - } - return $values; - } - - - /** - * @return array - */ - private function getPidS(): array - { - exec('ps -eo pid', $output); - return array_filter($output, function ($value) { - return intval($value); - }); - } - - - /** - * @param string $value - */ - public function close(mixed $value) - { - while ($this->pidIsExists($value)) { - exec('kill -15 ' . $value); - usleep(100); - } - clearstatcache($value); - if (file_exists($value)) { - @unlink($value); - } - } - - -} diff --git a/http-message/Request.php b/http-message/Request.php index 59ee6932..7f198052 100644 --- a/http-message/Request.php +++ b/http-message/Request.php @@ -3,7 +3,7 @@ namespace Http\Message; use BadMethodCallException; -use Http\IInterface\AuthIdentity; +use Http\Handler\AuthIdentity; use Psr\Http\Message\RequestInterface; use Psr\Http\Message\UriInterface; diff --git a/http-message/ServerRequest.php b/http-message/ServerRequest.php index 65ba3b33..46b7076a 100644 --- a/http-message/ServerRequest.php +++ b/http-message/ServerRequest.php @@ -2,7 +2,7 @@ namespace Http\Message; -use Http\Context\Context; +use Http\Handler\Context; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Message\StreamInterface; diff --git a/http-server/Abstracts/Http.php b/http-server/Abstracts/Http.php index 26312478..ed617068 100644 --- a/http-server/Abstracts/Http.php +++ b/http-server/Abstracts/Http.php @@ -3,14 +3,11 @@ namespace Server\Abstracts; use Annotation\Inject; -use Http\Route\Router; +use Http\Handler\Router; use Kiri\Abstracts\Config; use Kiri\Exception\ConfigException; -use Kiri\Exception\NotFindClassException; use Kiri\Kiri; -use ReflectionException; use Server\Constrict\ResponseEmitter; -use Server\Constrict\TcpEmitter; use Server\ExceptionHandlerDispatcher; use Server\ExceptionHandlerInterface; use Server\SInterface\OnRequest; diff --git a/http-server/Constrict/Request.php b/http-server/Constrict/Request.php index 9ee898bd..3dd05414 100644 --- a/http-server/Constrict/Request.php +++ b/http-server/Constrict/Request.php @@ -2,8 +2,8 @@ namespace Server\Constrict; -use Http\Context\Context; -use Http\IInterface\AuthIdentity; +use Http\Handler\Context; +use Http\Handler\AuthIdentity; use JetBrains\PhpStorm\Pure; use Kiri\Kiri; use Http\Message\Response; diff --git a/http-server/Constrict/RequestInterface.php b/http-server/Constrict/RequestInterface.php index f81f3136..a7e5d1ec 100644 --- a/http-server/Constrict/RequestInterface.php +++ b/http-server/Constrict/RequestInterface.php @@ -3,7 +3,7 @@ namespace Server\Constrict; -use Http\IInterface\AuthIdentity; +use Http\Handler\AuthIdentity; use JetBrains\PhpStorm\Pure; use Http\Message\ServerRequest; use Psr\Http\Message\UploadedFileInterface; diff --git a/http-server/Constrict/Response.php b/http-server/Constrict/Response.php index b7b4d363..c6519992 100644 --- a/http-server/Constrict/Response.php +++ b/http-server/Constrict/Response.php @@ -4,7 +4,7 @@ namespace Server\Constrict; -use Http\Context\Context; +use Http\Handler\Context; use JetBrains\PhpStorm\Pure; use Kiri\Kiri; use Psr\Http\Message\StreamInterface; diff --git a/http-server/Server.php b/http-server/Server.php index 1e1d2038..8510786a 100644 --- a/http-server/Server.php +++ b/http-server/Server.php @@ -5,7 +5,7 @@ namespace Server; use Annotation\Inject; use Exception; -use Http\Abstracts\HttpService; +use Http\Handler\Abstracts\HttpService; use JetBrains\PhpStorm\Pure; use Kiri\Abstracts\Config; use Kiri\Error\LoggerProcess; diff --git a/http-server/ServerManager.php b/http-server/ServerManager.php index 68446812..ca0a60f5 100644 --- a/http-server/ServerManager.php +++ b/http-server/ServerManager.php @@ -5,7 +5,6 @@ namespace Server; use Annotation\Inject; use Closure; use Exception; -use Http\Route\Router; use Kiri\Abstracts\Config; use Kiri\Di\ContainerInterface; use Kiri\Exception\ConfigException; @@ -169,12 +168,8 @@ class ServerManager $customProcess = Kiri::createObject($customProcess, [$server]); } - $namespace = array_filter(explode('\\', Router::getNamespace())); - - $namespace = APP_PATH . implode('/', $namespace); - $name = $customProcess->getProcessName($soloProcess); - scan_directory(directory('app'), 'App', [$namespace]); + scan_directory(directory('app'), 'App'); $system = sprintf('%s.process[%d]', Config::get('id', 'system-service'), $soloProcess->pid); if (Kiri::getPlatform()->isLinux()) { diff --git a/http-server/Service/Http.php b/http-server/Service/Http.php index 12dc0d71..a3ab72af 100644 --- a/http-server/Service/Http.php +++ b/http-server/Service/Http.php @@ -5,26 +5,18 @@ namespace Server\Service; use Annotation\Inject; use Exception; -use Http\Context\Context; -use Http\Exception\RequestException; +use Http\Handler\Context; use Http\Handler\Abstracts\HandlerManager; use Http\Handler\Dispatcher; use Http\Handler\Handler; -use Http\Handler\TestRequest; use Http\Message\ServerRequest; use Http\Message\Stream; -use Http\Route\MiddlewareManager; -use Http\Route\Node; -use Kiri\Core\Help; +use Http\Handler\Abstracts\MiddlewareManager; use Psr\Http\Message\ServerRequestInterface; -use Server\Constant; -use Server\Constrict\Request as ScRequest; use Server\Constrict\RequestInterface; use Server\Constrict\ResponseInterface; -use Server\Events\OnAfterRequest; use Server\SInterface\OnClose; use Server\SInterface\OnConnect; -use Swoole\Error; use Swoole\Http\Request; use Swoole\Http\Response; use Swoole\Server; diff --git a/http-server/Worker/OnWorkerStart.php b/http-server/Worker/OnWorkerStart.php index e6e531ef..e87a4f3a 100644 --- a/http-server/Worker/OnWorkerStart.php +++ b/http-server/Worker/OnWorkerStart.php @@ -5,7 +5,7 @@ namespace Server\Worker; use Annotation\Annotation; use Annotation\Inject; use Exception; -use Http\Route\Router; +use Http\Handler\Router; use Kiri\Abstracts\Config; use Kiri\Di\NoteManager; use Kiri\Exception\ConfigException; diff --git a/kiri-gii/GiiMiddleware.php b/kiri-gii/GiiMiddleware.php index 9080aef3..e0aa8446 100644 --- a/kiri-gii/GiiMiddleware.php +++ b/kiri-gii/GiiMiddleware.php @@ -33,7 +33,7 @@ class GiiMiddleware extends GiiBase namespace App\Http\Middleware; use Closure; -use Http\IInterface\MiddlewareInterface; +use Psr\Http\Server\MiddlewareInterface; use Server\Constrict\RequestInterface; '; diff --git a/kiri-gii/GiiRpcService.php b/kiri-gii/GiiRpcService.php index f36ca9bd..4128be12 100644 --- a/kiri-gii/GiiRpcService.php +++ b/kiri-gii/GiiRpcService.php @@ -37,7 +37,6 @@ use Annotation\Route\RpcProducer; use Annotation\Target; use Exception; use Http\Controller; -use Http\Exception\RequestException; use Kiri\Core\Json; '; diff --git a/kiri-gii/GiiTask.php b/kiri-gii/GiiTask.php index 33cad91d..2d9f5e24 100644 --- a/kiri-gii/GiiTask.php +++ b/kiri-gii/GiiTask.php @@ -31,7 +31,7 @@ class GiiTask extends GiiBase namespace App\Async; -use Http\IInterface\Task; +use Server\SInterface\TaskExecute; '; diff --git a/note/Asynchronous.php b/note/Asynchronous.php index 0bdca270..be8698f6 100644 --- a/note/Asynchronous.php +++ b/note/Asynchronous.php @@ -5,7 +5,6 @@ namespace Annotation; use Exception; -use Http\IInterface\Task; use Kiri\Kiri; diff --git a/note/Route/Middleware.php b/note/Route/Middleware.php index 0dfa6c09..f34b6a11 100644 --- a/note/Route/Middleware.php +++ b/note/Route/Middleware.php @@ -5,8 +5,8 @@ namespace Annotation\Route; use Annotation\Attribute; -use Http\IInterface\MiddlewareInterface; -use Http\Route\MiddlewareManager; +use Http\Handler\Abstracts\MiddlewareManager; +use Psr\Http\Server\MiddlewareInterface; /** * Class Middleware @@ -27,12 +27,12 @@ use Http\Route\MiddlewareManager; $this->middleware = [$this->middleware]; } $array = []; + + foreach ($this->middleware as $value) { - $sn = di($value); - if (!($sn instanceof MiddlewareInterface)) { - continue; + if (!in_array(MiddlewareInterface::class, class_implements($value))) { + throw new \Exception('The middleware'); } - $array[] = [$sn, 'onHandler']; } $this->middleware = $array; } diff --git a/note/Route/Socket.php b/note/Route/Socket.php index 3a04cfe4..88853fd9 100644 --- a/note/Route/Socket.php +++ b/note/Route/Socket.php @@ -5,9 +5,6 @@ namespace Annotation\Route; use Annotation\Attribute; -use Exception; -use Http\Route\Router; -use Kiri\Kiri; /** * Class Socket