Normal.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. namespace Qii\Route\Parse;
  3. /**
  4. * Route规则文件
  5. * 兼容以前版本的匹配规则
  6. *
  7. * @author Jinhui Zhu<jinhui.zhu@live.cn>2015-10-24 23:11
  8. * @version 1.2
  9. */
  10. class Normal
  11. {
  12. const VERSION = '1.2';
  13. private $config;
  14. public function __construct()
  15. {
  16. }
  17. /**
  18. * 设置路由规则
  19. * @param Array $config 路由规则
  20. */
  21. public function setConfig($config)
  22. {
  23. $this->config = $config;
  24. }
  25. /**
  26. * 路由转发, 转发对应的规则中xx不能为*
  27. *
  28. * @param string $url url链接
  29. * @param String $controller
  30. * @param String $action
  31. * @return Array ($controller, $action);
  32. *
  33. * *:* => *:yyy 所有controller和action都转发到 *->yyy
  34. * *:* => yy:* 所有转发到xxx->*, 这里的*,前边对应的是什么,后边就对应转发到什么,比如: *:xxx => yy:yyy
  35. * xx:* => yy:* xx中对应的方法转发到yy对应的方法
  36. * xx:* => yy:yyy xxx Controller转发到 yy->yyy
  37. * *:xxx => yy:yyy 所有Controller转发到 yy->yyy
  38. * xxx:*(yy):第三个参数 => {1}:* 转发xxx:yy => yy:第三个参数
  39. */
  40. public function parse($url, $controller, $action)
  41. {
  42. if (!$this->config) {
  43. return array('controller' => $controller, 'action' => $action);
  44. }
  45. $dirInfo = explode('/', pathinfo(ltrim($url, '/'), PATHINFO_DIRNAME));
  46. $fileName = pathinfo(ltrim($url, '/'), PATHINFO_FILENAME);
  47. $dirInfo[] = $fileName;
  48. $dir = '';
  49. $match = ['key' => '', 'val' => '', 'url' => $url];
  50. foreach($dirInfo AS $path)
  51. {
  52. $dir[] = $path;
  53. $joinPath = join($dir, ':') .":*";
  54. if(isset($this->config[$joinPath]))
  55. {
  56. $config = $this->config[$joinPath];
  57. //匹配最长的规则
  58. if(strlen($config) > strlen($match['val'])) {
  59. $match = array_merge($match, ['key' => $joinPath, 'val' => $config]);
  60. }
  61. }
  62. }
  63. $match['dirInfo'] = $dirInfo;
  64. //如果match到就解析match的内容
  65. if($match['val']) {
  66. $matches = explode(':', $match['val']);
  67. $match['matches'] = $matches;
  68. $action = array_pop($matches);
  69. $controller = join('\\', $matches);
  70. $controllerExplode = explode('\\', $controller);
  71. if(stristr($controller, '{1}')){
  72. $controller = join('\\', array_slice($dirInfo,0 , count($controllerExplode)));
  73. }
  74. $action = $action == '{1}' || $action == '*' ? isset($dirInfo[count($controllerExplode)]) ? $dirInfo[count($controllerExplode)] : 'index' : $action;
  75. $match['controller'] = $controller;
  76. $match['action'] = $action;
  77. }else{
  78. $match['controller'] = isset($dirInfo[0]) ? $dirInfo[0] : 'index';
  79. $match['action'] = isset($dirInfo[1]) ? $dirInfo[1] : 'index';
  80. }
  81. return $match;
  82. }
  83. }