Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 
 

107 rader
3.3 KiB

  1. <?php
  2. namespace Kuxin;
  3. /**
  4. * Class Router
  5. *
  6. * @package Kuxin
  7. * @author Pakey <pakey@qq.com>
  8. */
  9. class Router
  10. {
  11. static $controller = 'index';
  12. static $action = 'index';
  13. static $selfConsoleClass = [
  14. 'migrate',
  15. ];
  16. /**
  17. * 解析controller和action
  18. */
  19. public static function dispatcher(): void
  20. {
  21. //解析s变量
  22. if (isset($_GET['s'])) {
  23. $superVar = rtrim($_GET['s'], '/');
  24. //判断是否需要进行rewrite转换
  25. if (Config::get('rewrite.power')) {
  26. $superVar = self::rewrite($superVar);
  27. }
  28. if (strpos($superVar, '/')) {
  29. if (strpos($superVar, '.')) {
  30. $param = explode('.', $superVar, 2);
  31. if (!Request::isAjax()) {
  32. Response::setType($param['1']);
  33. }
  34. $param = explode('/', $param['0']);
  35. } else {
  36. $param = explode('/', $superVar);
  37. }
  38. self::$action = str_replace(['<', '>', '(', ')', '+'], '', strtolower(array_pop($param)));
  39. self::$controller = str_replace(['<', '>', '(', ')', '+'], '', strtolower(implode('\\', $param)));
  40. } else {
  41. self::$controller = str_replace(['<', '>', '(', ')', '+'], '', strtolower($superVar));
  42. self::$action = 'index';
  43. }
  44. self::$controller = self::$controller ?: 'index';
  45. self::$action = self::$action ?: 'index';
  46. unset($_GET['s']);
  47. unset($_REQUEST['s']);
  48. }
  49. }
  50. /**
  51. * 正则模式解析
  52. */
  53. public static function rewrite($superVar)
  54. {
  55. if ($router = Config::get('rewrite.router')) {
  56. foreach ($router as $rule => $url) {
  57. if (preg_match('{' . $rule . '}isU', $superVar, $match)) {
  58. unset($match['0']);
  59. if (strpos($url, '?')) {
  60. list($url, $query) = explode('?', $url);
  61. }
  62. $superVar = rtrim($url, '/');
  63. if ($match && !empty($query)) {//组合后面的参数
  64. $param = explode('&', $query);
  65. if (count($param) == count($match) && $var = array_combine($param, $match)) {
  66. $_GET = array_merge($_GET, $var);
  67. $_REQUEST = array_merge($_REQUEST, $var);
  68. }
  69. }
  70. break;
  71. }
  72. }
  73. }
  74. return $superVar;
  75. }
  76. /**
  77. * 命令行解析
  78. */
  79. public static function cli()
  80. {
  81. global $argv;
  82. if (strpos($argv['1'], ':')) {
  83. $param = explode(':', $argv['1']);
  84. self::$action = array_pop($param);
  85. self::$controller = implode('\\', $param);
  86. } else {
  87. self::$action = 'run';
  88. self::$controller = $argv['1'];
  89. }
  90. $data = ['argv' => $argv];
  91. if (!empty($argv['2'])) {
  92. $param = explode('/', $argv['2']);
  93. $num = count($param);
  94. for ($i = 0; $i < $num; $i += 2) {
  95. $data[$param[$i]] = $param[$i + 1] ?? "";
  96. }
  97. }
  98. Registry::set('cli_params', $data);
  99. }
  100. }