Middleware.php 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. <?php
  2. declare(strict_types=1);
  3. namespace Glacier\Core;
  4. /**
  5. * 中间件注册表与执行管道。
  6. * 中间件签名:function(array $params): void
  7. * - 通过:正常返回;
  8. * - 拒绝:调用 Response::xxx() 终止(403/重定向等)。
  9. * 本期落地:csrf(表单/API 校验);预留:auth / permission(空实现)。
  10. */
  11. final class Middleware
  12. {
  13. /** @var array<string, callable> */
  14. private static array $registry = [];
  15. public static function register(string $name, callable $middleware): void
  16. {
  17. self::$registry[$name] = $middleware;
  18. }
  19. public static function resolve(string $name): callable
  20. {
  21. if (!isset(self::$registry[$name])) {
  22. throw new \InvalidArgumentException("未注册的中间件: {$name}");
  23. }
  24. return self::$registry[$name];
  25. }
  26. /** 按顺序执行中间件链。 */
  27. public static function run(array $names, array $params): void
  28. {
  29. foreach ($names as $name) {
  30. $middleware = self::resolve($name);
  31. $middleware($params);
  32. }
  33. }
  34. }