Files
kiri-router/src/Base/Middleware.php
T

85 lines
1.6 KiB
PHP
Raw Normal View History

2023-04-15 23:29:27 +08:00
<?php
2023-04-16 01:24:30 +08:00
declare(strict_types=1);
2023-04-15 23:29:27 +08:00
namespace Kiri\Router\Base;
2023-04-15 23:31:16 +08:00
use Exception;
use Kiri\Core\HashMap;
use Psr\Http\Server\MiddlewareInterface;
2023-04-15 23:29:27 +08:00
class Middleware
{
2023-04-15 23:31:16 +08:00
public HashMap $map;
public HashMap $routeMap;
/**
*
*/
public function __construct()
{
$this->routeMap = new HashMap();
$this->map = new HashMap();
}
2023-04-16 12:44:43 +08:00
/**
* @param string $className
* @param string $method
* @param string $middleware
* @param array $construct
* @return void
* @throws Exception
*/
public function set(string $className, string $method, string $middleware, array $construct = []): void
{
$path = $className . '::' . $method;
if ($this->map->has($path)) {
$values = $this->map->get($path);
if (in_array($middleware, $values)) {
return;
}
if (!in_array(MiddlewareInterface::class, class_implements($middleware))) {
return;
}
}
$this->map->append($path, [$middleware, $construct]);
}
/**
* @param string $className
* @param string $method
* @return array
*/
public function get(string $className, string $method): array
{
return $this->routeMap->get($className . '::' . $method) ?? [];
}
2023-04-15 23:31:16 +08:00
/**
* @param string $path
* @param mixed $middleware
* @return void
* @throws Exception
*/
public function addPathMiddleware(string $path, string $middleware): void
{
if ($this->routeMap->has($path)) {
$values = $this->routeMap->get($path);
if (in_array($middleware, $values)) {
return;
}
if (!in_array(MiddlewareInterface::class, class_implements($middleware))) {
return;
}
}
$this->routeMap->append($path, $middleware);
}
2023-04-15 23:29:27 +08:00
}