Middleware.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. /**
  3. * This file is part of webman.
  4. *
  5. * Licensed under The MIT License
  6. * For full copyright and license information, please see the MIT-LICENSE.txt
  7. * Redistributions of files must retain the above copyright notice.
  8. *
  9. * @author walkor<walkor@workerman.net>
  10. * @copyright walkor<walkor@workerman.net>
  11. * @link http://www.workerman.net/
  12. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  13. */
  14. namespace Webman;
  15. use RuntimeException;
  16. use function array_merge;
  17. use function array_reverse;
  18. use function is_array;
  19. use function method_exists;
  20. class Middleware
  21. {
  22. /**
  23. * @var array
  24. */
  25. protected static $instances = [];
  26. /**
  27. * @param mixed $allMiddlewares
  28. * @param string $plugin
  29. * @return void
  30. */
  31. public static function load($allMiddlewares, string $plugin = '')
  32. {
  33. if (!is_array($allMiddlewares)) {
  34. return;
  35. }
  36. foreach ($allMiddlewares as $appName => $middlewares) {
  37. if (!is_array($middlewares)) {
  38. throw new RuntimeException('Bad middleware config');
  39. }
  40. if ($appName === '@') {
  41. $plugin = '';
  42. }
  43. if (strpos($appName, 'plugin.') !== false) {
  44. $explode = explode('.', $appName, 4);
  45. $plugin = $explode[1];
  46. $appName = $explode[2] ?? '';
  47. }
  48. foreach ($middlewares as $className) {
  49. if (method_exists($className, 'process')) {
  50. static::$instances[$plugin][$appName][] = [$className, 'process'];
  51. } else {
  52. // @todo Log
  53. echo "middleware $className::process not exsits\n";
  54. }
  55. }
  56. }
  57. }
  58. /**
  59. * @param string $plugin
  60. * @param string $appName
  61. * @param bool $withGlobalMiddleware
  62. * @return array|mixed
  63. */
  64. public static function getMiddleware(string $plugin, string $appName, bool $withGlobalMiddleware = true)
  65. {
  66. $globalMiddleware = static::$instances['']['@'] ?? [];
  67. $appGlobalMiddleware = $withGlobalMiddleware && isset(static::$instances[$plugin]['']) ? static::$instances[$plugin][''] : [];
  68. if ($appName === '') {
  69. return array_reverse(array_merge($globalMiddleware, $appGlobalMiddleware));
  70. }
  71. $appMiddleware = static::$instances[$plugin][$appName] ?? [];
  72. return array_reverse(array_merge($globalMiddleware, $appGlobalMiddleware, $appMiddleware));
  73. }
  74. /**
  75. * @return void
  76. * @deprecated
  77. */
  78. public static function container($_)
  79. {
  80. }
  81. }