This commit is contained in:
2021-09-17 18:55:08 +08:00
parent fc41341e3b
commit 1aabda2074
11 changed files with 428 additions and 1 deletions
+50
View File
@@ -0,0 +1,50 @@
<?php
namespace Http\Handler\Abstracts;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Http\Handler\Handler as CHl;
abstract class Handler implements RequestHandlerInterface
{
private int $offset = 0;
/**
* @param CHl $handler
* @param array|null $middlewares
*/
public function __construct(protected CHl $handler, protected ?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 call_user_func($this->handler->callback, ...$this->handler->params);
}
$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);
}
}
+50
View File
@@ -0,0 +1,50 @@
<?php
namespace Http\Handler\Abstracts;
use Closure;
use Kiri\Kiri;
class HandlerManager
{
private static array $handlers = [];
/**
* @param $path
* @param $method
* @param $handler
*/
public static function add($path, $method, $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;
}
if ($array instanceof Closure) {
return $array;
}
$array[1] = Kiri::getDi()->get($array[1]);
return $array;
}
}
+12
View File
@@ -0,0 +1,12 @@
<?php
namespace Http\Handler\Abstracts;
use Psr\Http\Server\MiddlewareInterface;
abstract class Middleware implements MiddlewareInterface
{
}