2021-07-27 03:30:55 +08:00
|
|
|
<?php
|
|
|
|
|
|
|
|
|
|
|
2021-09-18 16:54:39 +08:00
|
|
|
namespace Http\Handler\Abstracts;
|
2021-07-27 03:30:55 +08:00
|
|
|
|
|
|
|
|
|
2021-07-27 16:08:16 +08:00
|
|
|
use Closure;
|
2021-09-24 18:24:46 +08:00
|
|
|
use Co\Iterator;
|
2021-08-11 01:04:57 +08:00
|
|
|
use Kiri\Abstracts\BaseObject;
|
2021-07-27 03:30:55 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
2021-07-27 04:16:42 +08:00
|
|
|
* Class MiddlewareManager
|
2021-08-17 16:43:50 +08:00
|
|
|
* @package Http\Route
|
2021-07-27 03:30:55 +08:00
|
|
|
*/
|
2021-07-27 04:16:42 +08:00
|
|
|
class MiddlewareManager extends BaseObject
|
2021-07-27 03:30:55 +08:00
|
|
|
{
|
|
|
|
|
|
2021-09-24 18:42:30 +08:00
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* @var array<string, Iterator>
|
|
|
|
|
*/
|
2021-09-16 14:19:05 +08:00
|
|
|
private static array $_middlewares = [];
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* @param $class
|
|
|
|
|
* @param $method
|
|
|
|
|
* @param array|string $middlewares
|
|
|
|
|
* @return bool
|
|
|
|
|
*/
|
|
|
|
|
public static function add($class, $method, array|string $middlewares): bool
|
|
|
|
|
{
|
|
|
|
|
if (is_object($class)) {
|
|
|
|
|
$class = $class::class;
|
|
|
|
|
}
|
2021-09-20 03:09:00 +08:00
|
|
|
if (!isset(static::$_middlewares[$class])) {
|
|
|
|
|
static::$_middlewares[$class] = [];
|
2021-09-16 14:19:05 +08:00
|
|
|
}
|
2021-09-20 03:09:00 +08:00
|
|
|
if (!isset(static::$_middlewares[$class][$method])) {
|
2021-09-24 18:24:46 +08:00
|
|
|
static::$_middlewares[$class][$method] = new Iterator();
|
2021-09-20 03:09:00 +08:00
|
|
|
}
|
2021-09-24 17:59:30 +08:00
|
|
|
if (is_string($middlewares)) {
|
|
|
|
|
$middlewares = [$middlewares];
|
|
|
|
|
}
|
2021-09-24 18:24:46 +08:00
|
|
|
$source = static::$_middlewares[$class][$method];
|
2021-09-24 17:59:30 +08:00
|
|
|
foreach ($middlewares as $middleware) {
|
2021-09-24 18:14:38 +08:00
|
|
|
if (isset($source[$middleware])) {
|
2021-09-24 17:59:30 +08:00
|
|
|
continue;
|
2021-09-16 14:19:05 +08:00
|
|
|
}
|
2021-09-24 18:14:38 +08:00
|
|
|
$source[$middleware] = di($middleware);
|
2021-09-16 14:19:05 +08:00
|
|
|
}
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* @param $handler
|
2021-09-24 18:46:25 +08:00
|
|
|
* @return Iterator|null
|
2021-09-16 14:19:05 +08:00
|
|
|
*/
|
2021-09-24 18:46:25 +08:00
|
|
|
public static function get($handler): ?Iterator
|
2021-09-16 14:19:05 +08:00
|
|
|
{
|
2021-09-24 18:39:46 +08:00
|
|
|
if (!($handler instanceof Closure)) {
|
2021-09-24 18:46:25 +08:00
|
|
|
return static::$_middlewares[$handler[0]][$handler[1]] ?? null;
|
2021-09-16 14:19:05 +08:00
|
|
|
}
|
2021-09-24 18:42:30 +08:00
|
|
|
return di(Iterator::class);
|
2021-09-16 14:19:05 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
2021-07-27 03:30:55 +08:00
|
|
|
}
|