MiddlewareManager.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace Hyperf\HttpServer;
  12. use Hyperf\Stdlib\SplPriorityQueue;
  13. class MiddlewareManager
  14. {
  15. public static array $container = [];
  16. public static function addMiddleware(string $server, string $path, string $method, string $middleware): void
  17. {
  18. $method = strtoupper($method);
  19. static::$container[$server][$path][$method][] = $middleware;
  20. }
  21. public static function addMiddlewares(string $server, string $path, string $method, array $middlewares): void
  22. {
  23. $method = strtoupper($method);
  24. foreach ($middlewares as $middleware => $priority) {
  25. if ($priority instanceof PriorityMiddleware) {
  26. static::$container[$server][$path][$method][] = $priority;
  27. continue;
  28. }
  29. if (is_int($priority)) {
  30. static::$container[$server][$path][$method][] = new PriorityMiddleware($middleware, $priority);
  31. continue;
  32. }
  33. $middleware = $priority;
  34. static::$container[$server][$path][$method][] = $middleware;
  35. }
  36. }
  37. public static function get(string $server, string $rule, string $method): array
  38. {
  39. $method = strtoupper($method);
  40. if (isset(static::$container[$server][$rule][$method])) {
  41. return static::$container[$server][$rule][$method];
  42. }
  43. // For HEAD requests, attempt fallback to GET
  44. // keep the same with FastRoute\Dispatcher\RegexBasedAbstract::dispatch
  45. if ($method === 'HEAD') {
  46. $method = 'GET';
  47. }
  48. return static::$container[$server][$rule][$method] ?? [];
  49. }
  50. /**
  51. * @return string[]
  52. */
  53. public static function sortMiddlewares(array $middlewares): array
  54. {
  55. $queue = new SplPriorityQueue();
  56. foreach ($middlewares as $middleware => $priority) {
  57. if ($priority instanceof PriorityMiddleware) {
  58. // int => Hyperf\HttpServer\MiddlewareData Object
  59. [$middleware, $priority] = [$priority->middleware, $priority->priority];
  60. } elseif (is_int($middleware)) {
  61. // int => Middleware::class
  62. [$middleware, $priority] = [$priority, PriorityMiddleware::DEFAULT_PRIORITY];
  63. }
  64. // Default Middleware::class => priority
  65. $queue->insert($middleware, $priority);
  66. }
  67. return array_unique($queue->toArray());
  68. }
  69. }