You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Route.php 60 KiB

4 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: liu21st <liu21st@gmail.com>
  10. // +----------------------------------------------------------------------
  11. namespace think;
  12. use think\exception\HttpException;
  13. class Route
  14. {
  15. // 路由规则
  16. private static $rules = [
  17. 'get' => [],
  18. 'post' => [],
  19. 'put' => [],
  20. 'delete' => [],
  21. 'patch' => [],
  22. 'head' => [],
  23. 'options' => [],
  24. '*' => [],
  25. 'alias' => [],
  26. 'domain' => [],
  27. 'pattern' => [],
  28. 'name' => [],
  29. ];
  30. // REST路由操作方法定义
  31. private static $rest = [
  32. 'index' => ['get', '', 'index'],
  33. 'create' => ['get', '/create', 'create'],
  34. 'edit' => ['get', '/:id/edit', 'edit'],
  35. 'read' => ['get', '/:id', 'read'],
  36. 'save' => ['post', '', 'save'],
  37. 'update' => ['put', '/:id', 'update'],
  38. 'delete' => ['delete', '/:id', 'delete'],
  39. ];
  40. // 不同请求类型的方法前缀
  41. private static $methodPrefix = [
  42. 'get' => 'get',
  43. 'post' => 'post',
  44. 'put' => 'put',
  45. 'delete' => 'delete',
  46. 'patch' => 'patch',
  47. ];
  48. // 子域名
  49. private static $subDomain = '';
  50. // 域名绑定
  51. private static $bind = [];
  52. // 当前分组信息
  53. private static $group = [];
  54. // 当前子域名绑定
  55. private static $domainBind;
  56. private static $domainRule;
  57. // 当前域名
  58. private static $domain;
  59. // 当前路由执行过程中的参数
  60. private static $option = [];
  61. /**
  62. * 注册变量规则
  63. * @access public
  64. * @param string|array $name 变量名
  65. * @param string $rule 变量规则
  66. * @return void
  67. */
  68. public static function pattern($name = null, $rule = '')
  69. {
  70. if (is_array($name)) {
  71. self::$rules['pattern'] = array_merge(self::$rules['pattern'], $name);
  72. } else {
  73. self::$rules['pattern'][$name] = $rule;
  74. }
  75. }
  76. /**
  77. * 注册子域名部署规则
  78. * @access public
  79. * @param string|array $domain 子域名
  80. * @param mixed $rule 路由规则
  81. * @param array $option 路由参数
  82. * @param array $pattern 变量规则
  83. * @return void
  84. */
  85. public static function domain($domain, $rule = '', $option = [], $pattern = [])
  86. {
  87. if (is_array($domain)) {
  88. foreach ($domain as $key => $item) {
  89. self::domain($key, $item, $option, $pattern);
  90. }
  91. } elseif ($rule instanceof \Closure) {
  92. // 执行闭包
  93. self::setDomain($domain);
  94. call_user_func_array($rule, []);
  95. self::setDomain(null);
  96. } elseif (is_array($rule)) {
  97. self::setDomain($domain);
  98. self::group('', function () use ($rule) {
  99. // 动态注册域名的路由规则
  100. self::registerRules($rule);
  101. }, $option, $pattern);
  102. self::setDomain(null);
  103. } else {
  104. self::$rules['domain'][$domain]['[bind]'] = [$rule, $option, $pattern];
  105. }
  106. }
  107. private static function setDomain($domain)
  108. {
  109. self::$domain = $domain;
  110. }
  111. /**
  112. * 设置路由绑定
  113. * @access public
  114. * @param mixed $bind 绑定信息
  115. * @param string $type 绑定类型 默认为module 支持 namespace class controller
  116. * @return mixed
  117. */
  118. public static function bind($bind, $type = 'module')
  119. {
  120. self::$bind = ['type' => $type, $type => $bind];
  121. }
  122. /**
  123. * 设置或者获取路由标识
  124. * @access public
  125. * @param string|array $name 路由命名标识 数组表示批量设置
  126. * @param array $value 路由地址及变量信息
  127. * @return array
  128. */
  129. public static function name($name = '', $value = null)
  130. {
  131. if (is_array($name)) {
  132. return self::$rules['name'] = $name;
  133. } elseif ('' === $name) {
  134. return self::$rules['name'];
  135. } elseif (!is_null($value)) {
  136. self::$rules['name'][strtolower($name)][] = $value;
  137. } else {
  138. $name = strtolower($name);
  139. return isset(self::$rules['name'][$name]) ? self::$rules['name'][$name] : null;
  140. }
  141. }
  142. /**
  143. * 读取路由绑定
  144. * @access public
  145. * @param string $type 绑定类型
  146. * @return mixed
  147. */
  148. public static function getBind($type)
  149. {
  150. return isset(self::$bind[$type]) ? self::$bind[$type] : null;
  151. }
  152. /**
  153. * 导入配置文件的路由规则
  154. * @access public
  155. * @param array $rule 路由规则
  156. * @param string $type 请求类型
  157. * @return void
  158. */
  159. public static function import(array $rule, $type = '*')
  160. {
  161. // 检查域名部署
  162. if (isset($rule['__domain__'])) {
  163. self::domain($rule['__domain__']);
  164. unset($rule['__domain__']);
  165. }
  166. // 检查变量规则
  167. if (isset($rule['__pattern__'])) {
  168. self::pattern($rule['__pattern__']);
  169. unset($rule['__pattern__']);
  170. }
  171. // 检查路由别名
  172. if (isset($rule['__alias__'])) {
  173. self::alias($rule['__alias__']);
  174. unset($rule['__alias__']);
  175. }
  176. // 检查资源路由
  177. if (isset($rule['__rest__'])) {
  178. self::resource($rule['__rest__']);
  179. unset($rule['__rest__']);
  180. }
  181. self::registerRules($rule, strtolower($type));
  182. }
  183. // 批量注册路由
  184. protected static function registerRules($rules, $type = '*')
  185. {
  186. foreach ($rules as $key => $val) {
  187. if (is_numeric($key)) {
  188. $key = array_shift($val);
  189. }
  190. if (empty($val)) {
  191. continue;
  192. }
  193. if (is_string($key) && 0 === strpos($key, '[')) {
  194. $key = substr($key, 1, -1);
  195. self::group($key, $val);
  196. } elseif (is_array($val)) {
  197. self::setRule($key, $val[0], $type, $val[1], isset($val[2]) ? $val[2] : []);
  198. } else {
  199. self::setRule($key, $val, $type);
  200. }
  201. }
  202. }
  203. /**
  204. * 注册路由规则
  205. * @access public
  206. * @param string|array $rule 路由规则
  207. * @param string $route 路由地址
  208. * @param string $type 请求类型
  209. * @param array $option 路由参数
  210. * @param array $pattern 变量规则
  211. * @return void
  212. */
  213. public static function rule($rule, $route = '', $type = '*', $option = [], $pattern = [])
  214. {
  215. $group = self::getGroup('name');
  216. if (!is_null($group)) {
  217. // 路由分组
  218. $option = array_merge(self::getGroup('option'), $option);
  219. $pattern = array_merge(self::getGroup('pattern'), $pattern);
  220. }
  221. $type = strtolower($type);
  222. if (strpos($type, '|')) {
  223. $option['method'] = $type;
  224. $type = '*';
  225. }
  226. if (is_array($rule) && empty($route)) {
  227. foreach ($rule as $key => $val) {
  228. if (is_numeric($key)) {
  229. $key = array_shift($val);
  230. }
  231. if (is_array($val)) {
  232. $route = $val[0];
  233. $option1 = array_merge($option, $val[1]);
  234. $pattern1 = array_merge($pattern, isset($val[2]) ? $val[2] : []);
  235. } else {
  236. $option1 = null;
  237. $pattern1 = null;
  238. $route = $val;
  239. }
  240. self::setRule($key, $route, $type, !is_null($option1) ? $option1 : $option, !is_null($pattern1) ? $pattern1 : $pattern, $group);
  241. }
  242. } else {
  243. self::setRule($rule, $route, $type, $option, $pattern, $group);
  244. }
  245. }
  246. /**
  247. * 设置路由规则
  248. * @access public
  249. * @param string|array $rule 路由规则
  250. * @param string $route 路由地址
  251. * @param string $type 请求类型
  252. * @param array $option 路由参数
  253. * @param array $pattern 变量规则
  254. * @param string $group 所属分组
  255. * @return void
  256. */
  257. protected static function setRule($rule, $route, $type = '*', $option = [], $pattern = [], $group = '')
  258. {
  259. if (is_array($rule)) {
  260. $name = $rule[0];
  261. $rule = $rule[1];
  262. } elseif (is_string($route)) {
  263. $name = $route;
  264. }
  265. if (!isset($option['complete_match'])) {
  266. if (Config::get('route_complete_match')) {
  267. $option['complete_match'] = true;
  268. } elseif ('$' == substr($rule, -1, 1)) {
  269. // 是否完整匹配
  270. $option['complete_match'] = true;
  271. }
  272. } elseif (empty($option['complete_match']) && '$' == substr($rule, -1, 1)) {
  273. // 是否完整匹配
  274. $option['complete_match'] = true;
  275. }
  276. if ('$' == substr($rule, -1, 1)) {
  277. $rule = substr($rule, 0, -1);
  278. }
  279. if ('/' != $rule || $group) {
  280. $rule = trim($rule, '/');
  281. }
  282. $vars = self::parseVar($rule);
  283. if (isset($name)) {
  284. $key = $group ? $group . ($rule ? '/' . $rule : '') : $rule;
  285. $suffix = isset($option['ext']) ? $option['ext'] : null;
  286. self::name($name, [$key, $vars, self::$domain, $suffix]);
  287. }
  288. if (isset($option['modular'])) {
  289. $route = $option['modular'] . '/' . $route;
  290. }
  291. if ($group) {
  292. if ('*' != $type) {
  293. $option['method'] = $type;
  294. }
  295. if (self::$domain) {
  296. self::$rules['domain'][self::$domain]['*'][$group]['rule'][] = ['rule' => $rule, 'route' => $route, 'var' => $vars, 'option' => $option, 'pattern' => $pattern];
  297. } else {
  298. self::$rules['*'][$group]['rule'][] = ['rule' => $rule, 'route' => $route, 'var' => $vars, 'option' => $option, 'pattern' => $pattern];
  299. }
  300. } else {
  301. if ('*' != $type && isset(self::$rules['*'][$rule])) {
  302. unset(self::$rules['*'][$rule]);
  303. }
  304. if (self::$domain) {
  305. self::$rules['domain'][self::$domain][$type][$rule] = ['rule' => $rule, 'route' => $route, 'var' => $vars, 'option' => $option, 'pattern' => $pattern];
  306. } else {
  307. self::$rules[$type][$rule] = ['rule' => $rule, 'route' => $route, 'var' => $vars, 'option' => $option, 'pattern' => $pattern];
  308. }
  309. if ('*' == $type) {
  310. // 注册路由快捷方式
  311. foreach (['get', 'post', 'put', 'delete', 'patch', 'head', 'options'] as $method) {
  312. if (self::$domain && !isset(self::$rules['domain'][self::$domain][$method][$rule])) {
  313. self::$rules['domain'][self::$domain][$method][$rule] = true;
  314. } elseif (!self::$domain && !isset(self::$rules[$method][$rule])) {
  315. self::$rules[$method][$rule] = true;
  316. }
  317. }
  318. }
  319. }
  320. }
  321. /**
  322. * 设置当前执行的参数信息
  323. * @access public
  324. * @param array $options 参数信息
  325. * @return mixed
  326. */
  327. protected static function setOption($options = [])
  328. {
  329. self::$option[] = $options;
  330. }
  331. /**
  332. * 获取当前执行的所有参数信息
  333. * @access public
  334. * @return array
  335. */
  336. public static function getOption()
  337. {
  338. return self::$option;
  339. }
  340. /**
  341. * 获取当前的分组信息
  342. * @access public
  343. * @param string $type 分组信息名称 name option pattern
  344. * @return mixed
  345. */
  346. public static function getGroup($type)
  347. {
  348. if (isset(self::$group[$type])) {
  349. return self::$group[$type];
  350. } else {
  351. return 'name' == $type ? null : [];
  352. }
  353. }
  354. /**
  355. * 设置当前的路由分组
  356. * @access public
  357. * @param string $name 分组名称
  358. * @param array $option 分组路由参数
  359. * @param array $pattern 分组变量规则
  360. * @return void
  361. */
  362. public static function setGroup($name, $option = [], $pattern = [])
  363. {
  364. self::$group['name'] = $name;
  365. self::$group['option'] = $option ?: [];
  366. self::$group['pattern'] = $pattern ?: [];
  367. }
  368. /**
  369. * 注册路由分组
  370. * @access public
  371. * @param string|array $name 分组名称或者参数
  372. * @param array|\Closure $routes 路由地址
  373. * @param array $option 路由参数
  374. * @param array $pattern 变量规则
  375. * @return void
  376. */
  377. public static function group($name, $routes, $option = [], $pattern = [])
  378. {
  379. if (is_array($name)) {
  380. $option = $name;
  381. $name = isset($option['name']) ? $option['name'] : '';
  382. }
  383. // 分组
  384. $currentGroup = self::getGroup('name');
  385. if ($currentGroup) {
  386. $name = $currentGroup . ($name ? '/' . ltrim($name, '/') : '');
  387. }
  388. if (!empty($name)) {
  389. if ($routes instanceof \Closure) {
  390. $currentOption = self::getGroup('option');
  391. $currentPattern = self::getGroup('pattern');
  392. self::setGroup($name, array_merge($currentOption, $option), array_merge($currentPattern, $pattern));
  393. call_user_func_array($routes, []);
  394. self::setGroup($currentGroup, $currentOption, $currentPattern);
  395. if ($currentGroup != $name) {
  396. self::$rules['*'][$name]['route'] = '';
  397. self::$rules['*'][$name]['var'] = self::parseVar($name);
  398. self::$rules['*'][$name]['option'] = $option;
  399. self::$rules['*'][$name]['pattern'] = $pattern;
  400. }
  401. } else {
  402. $item = [];
  403. $completeMatch = Config::get('route_complete_match');
  404. foreach ($routes as $key => $val) {
  405. if (is_numeric($key)) {
  406. $key = array_shift($val);
  407. }
  408. if (is_array($val)) {
  409. $route = $val[0];
  410. $option1 = array_merge($option, isset($val[1]) ? $val[1] : []);
  411. $pattern1 = array_merge($pattern, isset($val[2]) ? $val[2] : []);
  412. } else {
  413. $route = $val;
  414. }
  415. $options = isset($option1) ? $option1 : $option;
  416. $patterns = isset($pattern1) ? $pattern1 : $pattern;
  417. if ('$' == substr($key, -1, 1)) {
  418. // 是否完整匹配
  419. $options['complete_match'] = true;
  420. $key = substr($key, 0, -1);
  421. } elseif ($completeMatch) {
  422. $options['complete_match'] = true;
  423. }
  424. $key = trim($key, '/');
  425. $vars = self::parseVar($key);
  426. $item[] = ['rule' => $key, 'route' => $route, 'var' => $vars, 'option' => $options, 'pattern' => $patterns];
  427. // 设置路由标识
  428. $suffix = isset($options['ext']) ? $options['ext'] : null;
  429. self::name($route, [$name . ($key ? '/' . $key : ''), $vars, self::$domain, $suffix]);
  430. }
  431. self::$rules['*'][$name] = ['rule' => $item, 'route' => '', 'var' => [], 'option' => $option, 'pattern' => $pattern];
  432. }
  433. foreach (['get', 'post', 'put', 'delete', 'patch', 'head', 'options'] as $method) {
  434. if (!isset(self::$rules[$method][$name])) {
  435. self::$rules[$method][$name] = true;
  436. } elseif (is_array(self::$rules[$method][$name])) {
  437. self::$rules[$method][$name] = array_merge(self::$rules['*'][$name], self::$rules[$method][$name]);
  438. }
  439. }
  440. } elseif ($routes instanceof \Closure) {
  441. // 闭包注册
  442. $currentOption = self::getGroup('option');
  443. $currentPattern = self::getGroup('pattern');
  444. self::setGroup('', array_merge($currentOption, $option), array_merge($currentPattern, $pattern));
  445. call_user_func_array($routes, []);
  446. self::setGroup($currentGroup, $currentOption, $currentPattern);
  447. } else {
  448. // 批量注册路由
  449. self::rule($routes, '', '*', $option, $pattern);
  450. }
  451. }
  452. /**
  453. * 注册路由
  454. * @access public
  455. * @param string|array $rule 路由规则
  456. * @param string $route 路由地址
  457. * @param array $option 路由参数
  458. * @param array $pattern 变量规则
  459. * @return void
  460. */
  461. public static function any($rule, $route = '', $option = [], $pattern = [])
  462. {
  463. self::rule($rule, $route, '*', $option, $pattern);
  464. }
  465. /**
  466. * 注册GET路由
  467. * @access public
  468. * @param string|array $rule 路由规则
  469. * @param string $route 路由地址
  470. * @param array $option 路由参数
  471. * @param array $pattern 变量规则
  472. * @return void
  473. */
  474. public static function get($rule, $route = '', $option = [], $pattern = [])
  475. {
  476. self::rule($rule, $route, 'GET', $option, $pattern);
  477. }
  478. /**
  479. * 注册POST路由
  480. * @access public
  481. * @param string|array $rule 路由规则
  482. * @param string $route 路由地址
  483. * @param array $option 路由参数
  484. * @param array $pattern 变量规则
  485. * @return void
  486. */
  487. public static function post($rule, $route = '', $option = [], $pattern = [])
  488. {
  489. self::rule($rule, $route, 'POST', $option, $pattern);
  490. }
  491. /**
  492. * 注册PUT路由
  493. * @access public
  494. * @param string|array $rule 路由规则
  495. * @param string $route 路由地址
  496. * @param array $option 路由参数
  497. * @param array $pattern 变量规则
  498. * @return void
  499. */
  500. public static function put($rule, $route = '', $option = [], $pattern = [])
  501. {
  502. self::rule($rule, $route, 'PUT', $option, $pattern);
  503. }
  504. /**
  505. * 注册DELETE路由
  506. * @access public
  507. * @param string|array $rule 路由规则
  508. * @param string $route 路由地址
  509. * @param array $option 路由参数
  510. * @param array $pattern 变量规则
  511. * @return void
  512. */
  513. public static function delete($rule, $route = '', $option = [], $pattern = [])
  514. {
  515. self::rule($rule, $route, 'DELETE', $option, $pattern);
  516. }
  517. /**
  518. * 注册PATCH路由
  519. * @access public
  520. * @param string|array $rule 路由规则
  521. * @param string $route 路由地址
  522. * @param array $option 路由参数
  523. * @param array $pattern 变量规则
  524. * @return void
  525. */
  526. public static function patch($rule, $route = '', $option = [], $pattern = [])
  527. {
  528. self::rule($rule, $route, 'PATCH', $option, $pattern);
  529. }
  530. /**
  531. * 注册资源路由
  532. * @access public
  533. * @param string|array $rule 路由规则
  534. * @param string $route 路由地址
  535. * @param array $option 路由参数
  536. * @param array $pattern 变量规则
  537. * @return void
  538. */
  539. public static function resource($rule, $route = '', $option = [], $pattern = [])
  540. {
  541. if (is_array($rule)) {
  542. foreach ($rule as $key => $val) {
  543. if (is_array($val)) {
  544. list($val, $option, $pattern) = array_pad($val, 3, []);
  545. }
  546. self::resource($key, $val, $option, $pattern);
  547. }
  548. } else {
  549. if (strpos($rule, '.')) {
  550. // 注册嵌套资源路由
  551. $array = explode('.', $rule);
  552. $last = array_pop($array);
  553. $item = [];
  554. foreach ($array as $val) {
  555. $item[] = $val . '/:' . (isset($option['var'][$val]) ? $option['var'][$val] : $val . '_id');
  556. }
  557. $rule = implode('/', $item) . '/' . $last;
  558. }
  559. // 注册资源路由
  560. foreach (self::$rest as $key => $val) {
  561. if ((isset($option['only']) && !in_array($key, $option['only']))
  562. || (isset($option['except']) && in_array($key, $option['except']))) {
  563. continue;
  564. }
  565. if (isset($last) && strpos($val[1], ':id') && isset($option['var'][$last])) {
  566. $val[1] = str_replace(':id', ':' . $option['var'][$last], $val[1]);
  567. } elseif (strpos($val[1], ':id') && isset($option['var'][$rule])) {
  568. $val[1] = str_replace(':id', ':' . $option['var'][$rule], $val[1]);
  569. }
  570. $item = ltrim($rule . $val[1], '/');
  571. $option['rest'] = $key;
  572. self::rule($item . '$', $route . '/' . $val[2], $val[0], $option, $pattern);
  573. }
  574. }
  575. }
  576. /**
  577. * 注册控制器路由 操作方法对应不同的请求后缀
  578. * @access public
  579. * @param string $rule 路由规则
  580. * @param string $route 路由地址
  581. * @param array $option 路由参数
  582. * @param array $pattern 变量规则
  583. * @return void
  584. */
  585. public static function controller($rule, $route = '', $option = [], $pattern = [])
  586. {
  587. foreach (self::$methodPrefix as $type => $val) {
  588. self::$type($rule . '/:action', $route . '/' . $val . ':action', $option, $pattern);
  589. }
  590. }
  591. /**
  592. * 注册别名路由
  593. * @access public
  594. * @param string|array $rule 路由别名
  595. * @param string $route 路由地址
  596. * @param array $option 路由参数
  597. * @return void
  598. */
  599. public static function alias($rule = null, $route = '', $option = [])
  600. {
  601. if (is_array($rule)) {
  602. self::$rules['alias'] = array_merge(self::$rules['alias'], $rule);
  603. } else {
  604. self::$rules['alias'][$rule] = $option ? [$route, $option] : $route;
  605. }
  606. }
  607. /**
  608. * 设置不同请求类型下面的方法前缀
  609. * @access public
  610. * @param string $method 请求类型
  611. * @param string $prefix 类型前缀
  612. * @return void
  613. */
  614. public static function setMethodPrefix($method, $prefix = '')
  615. {
  616. if (is_array($method)) {
  617. self::$methodPrefix = array_merge(self::$methodPrefix, array_change_key_case($method));
  618. } else {
  619. self::$methodPrefix[strtolower($method)] = $prefix;
  620. }
  621. }
  622. /**
  623. * rest方法定义和修改
  624. * @access public
  625. * @param string|array $name 方法名称
  626. * @param array|bool $resource 资源
  627. * @return void
  628. */
  629. public static function rest($name, $resource = [])
  630. {
  631. if (is_array($name)) {
  632. self::$rest = $resource ? $name : array_merge(self::$rest, $name);
  633. } else {
  634. self::$rest[$name] = $resource;
  635. }
  636. }
  637. /**
  638. * 注册未匹配路由规则后的处理
  639. * @access public
  640. * @param string $route 路由地址
  641. * @param string $method 请求类型
  642. * @param array $option 路由参数
  643. * @return void
  644. */
  645. public static function miss($route, $method = '*', $option = [])
  646. {
  647. self::rule('__miss__', $route, $method, $option, []);
  648. }
  649. /**
  650. * 注册一个自动解析的URL路由
  651. * @access public
  652. * @param string $route 路由地址
  653. * @return void
  654. */
  655. public static function auto($route)
  656. {
  657. self::rule('__auto__', $route, '*', [], []);
  658. }
  659. /**
  660. * 获取或者批量设置路由定义
  661. * @access public
  662. * @param mixed $rules 请求类型或者路由定义数组
  663. * @return array
  664. */
  665. public static function rules($rules = '')
  666. {
  667. if (is_array($rules)) {
  668. self::$rules = $rules;
  669. } elseif ($rules) {
  670. return true === $rules ? self::$rules : self::$rules[strtolower($rules)];
  671. } else {
  672. $rules = self::$rules;
  673. unset($rules['pattern'], $rules['alias'], $rules['domain'], $rules['name']);
  674. return $rules;
  675. }
  676. }
  677. /**
  678. * 检测子域名部署
  679. * @access public
  680. * @param Request $request Request请求对象
  681. * @param array $currentRules 当前路由规则
  682. * @param string $method 请求类型
  683. * @return void
  684. */
  685. public static function checkDomain($request, &$currentRules, $method = 'get')
  686. {
  687. // 域名规则
  688. $rules = self::$rules['domain'];
  689. // 开启子域名部署 支持二级和三级域名
  690. if (!empty($rules)) {
  691. $host = $request->host(true);
  692. if (isset($rules[$host])) {
  693. // 完整域名或者IP配置
  694. $item = $rules[$host];
  695. } else {
  696. $rootDomain = Config::get('url_domain_root');
  697. if ($rootDomain) {
  698. // 配置域名根 例如 thinkphp.cn 163.com.cn 如果是国家级域名 com.cn net.cn 之类的域名需要配置
  699. $domain = explode('.', rtrim(stristr($host, $rootDomain, true), '.'));
  700. } else {
  701. $domain = explode('.', $host, -2);
  702. }
  703. // 子域名配置
  704. if (!empty($domain)) {
  705. // 当前子域名
  706. $subDomain = implode('.', $domain);
  707. self::$subDomain = $subDomain;
  708. $domain2 = array_pop($domain);
  709. if ($domain) {
  710. // 存在三级域名
  711. $domain3 = array_pop($domain);
  712. }
  713. if ($subDomain && isset($rules[$subDomain])) {
  714. // 子域名配置
  715. $item = $rules[$subDomain];
  716. } elseif (isset($rules['*.' . $domain2]) && !empty($domain3)) {
  717. // 泛三级域名
  718. $item = $rules['*.' . $domain2];
  719. $panDomain = $domain3;
  720. } elseif (isset($rules['*']) && !empty($domain2)) {
  721. // 泛二级域名
  722. if ('www' != $domain2) {
  723. $item = $rules['*'];
  724. $panDomain = $domain2;
  725. }
  726. }
  727. }
  728. }
  729. if (!empty($item)) {
  730. if (isset($panDomain)) {
  731. // 保存当前泛域名
  732. $request->route(['__domain__' => $panDomain]);
  733. }
  734. if (isset($item['[bind]'])) {
  735. // 解析子域名部署规则
  736. list($rule, $option, $pattern) = $item['[bind]'];
  737. if (!empty($option['https']) && !$request->isSsl()) {
  738. // https检测
  739. throw new HttpException(404, 'must use https request:' . $host);
  740. }
  741. if (strpos($rule, '?')) {
  742. // 传入其它参数
  743. $array = parse_url($rule);
  744. $result = $array['path'];
  745. parse_str($array['query'], $params);
  746. if (isset($panDomain)) {
  747. $pos = array_search('*', $params);
  748. if (false !== $pos) {
  749. // 泛域名作为参数
  750. $params[$pos] = $panDomain;
  751. }
  752. }
  753. $_GET = array_merge($_GET, $params);
  754. } else {
  755. $result = $rule;
  756. }
  757. if (0 === strpos($result, '\\')) {
  758. // 绑定到命名空间 例如 \app\index\behavior
  759. self::$bind = ['type' => 'namespace', 'namespace' => $result];
  760. } elseif (0 === strpos($result, '@')) {
  761. // 绑定到类 例如 @app\index\controller\User
  762. self::$bind = ['type' => 'class', 'class' => substr($result, 1)];
  763. } else {
  764. // 绑定到模块/控制器 例如 index/user
  765. self::$bind = ['type' => 'module', 'module' => $result];
  766. }
  767. self::$domainBind = true;
  768. } else {
  769. self::$domainRule = $item;
  770. $currentRules = isset($item[$method]) ? $item[$method] : $item['*'];
  771. }
  772. }
  773. }
  774. }
  775. /**
  776. * 检测URL路由
  777. * @access public
  778. * @param Request $request Request请求对象
  779. * @param string $url URL地址
  780. * @param string $depr URL分隔符
  781. * @param bool $checkDomain 是否检测域名规则
  782. * @return false|array
  783. */
  784. public static function check($request, $url, $depr = '/', $checkDomain = false)
  785. {
  786. //检查解析缓存
  787. if (!App::$debug && Config::get('route_check_cache')) {
  788. $key = self::getCheckCacheKey($request);
  789. if (Cache::has($key)) {
  790. list($rule, $route, $pathinfo, $option, $matches) = Cache::get($key);
  791. return self::parseRule($rule, $route, $pathinfo, $option, $matches, true);
  792. }
  793. }
  794. // 分隔符替换 确保路由定义使用统一的分隔符
  795. $url = str_replace($depr, '|', $url);
  796. if (isset(self::$rules['alias'][$url]) || isset(self::$rules['alias'][strstr($url, '|', true)])) {
  797. // 检测路由别名
  798. $result = self::checkRouteAlias($request, $url, $depr);
  799. if (false !== $result) {
  800. return $result;
  801. }
  802. }
  803. $method = strtolower($request->method());
  804. // 获取当前请求类型的路由规则
  805. $rules = isset(self::$rules[$method]) ? self::$rules[$method] : [];
  806. // 检测域名部署
  807. if ($checkDomain) {
  808. self::checkDomain($request, $rules, $method);
  809. }
  810. // 检测URL绑定
  811. $return = self::checkUrlBind($url, $rules, $depr);
  812. if (false !== $return) {
  813. return $return;
  814. }
  815. if ('|' != $url) {
  816. $url = rtrim($url, '|');
  817. }
  818. $item = str_replace('|', '/', $url);
  819. if (isset($rules[$item])) {
  820. // 静态路由规则检测
  821. $rule = $rules[$item];
  822. if (true === $rule) {
  823. $rule = self::getRouteExpress($item);
  824. }
  825. if (!empty($rule['route']) && self::checkOption($rule['option'], $request)) {
  826. self::setOption($rule['option']);
  827. return self::parseRule($item, $rule['route'], $url, $rule['option']);
  828. }
  829. }
  830. // 路由规则检测
  831. if (!empty($rules)) {
  832. return self::checkRoute($request, $rules, $url, $depr);
  833. }
  834. return false;
  835. }
  836. private static function getRouteExpress($key)
  837. {
  838. return self::$domainRule ? self::$domainRule['*'][$key] : self::$rules['*'][$key];
  839. }
  840. /**
  841. * 检测路由规则
  842. * @access private
  843. * @param Request $request
  844. * @param array $rules 路由规则
  845. * @param string $url URL地址
  846. * @param string $depr URL分割符
  847. * @param string $group 路由分组名
  848. * @param array $options 路由参数(分组)
  849. * @return mixed
  850. */
  851. private static function checkRoute($request, $rules, $url, $depr = '/', $group = '', $options = [])
  852. {
  853. foreach ($rules as $key => $item) {
  854. if (true === $item) {
  855. $item = self::getRouteExpress($key);
  856. }
  857. if (!isset($item['rule'])) {
  858. continue;
  859. }
  860. $rule = $item['rule'];
  861. $route = $item['route'];
  862. $vars = $item['var'];
  863. $option = $item['option'];
  864. $pattern = $item['pattern'];
  865. // 检查参数有效性
  866. if (!self::checkOption($option, $request)) {
  867. continue;
  868. }
  869. if (isset($option['ext'])) {
  870. // 路由ext参数 优先于系统配置的URL伪静态后缀参数
  871. $url = preg_replace('/\.' . $request->ext() . '$/i', '', $url);
  872. }
  873. if (is_array($rule)) {
  874. // 分组路由
  875. $pos = strpos(str_replace('<', ':', $key), ':');
  876. if (false !== $pos) {
  877. $str = substr($key, 0, $pos);
  878. } else {
  879. $str = $key;
  880. }
  881. if (is_string($str) && $str && 0 !== stripos(str_replace('|', '/', $url), $str)) {
  882. continue;
  883. }
  884. self::setOption($option);
  885. $result = self::checkRoute($request, $rule, $url, $depr, $key, $option);
  886. if (false !== $result) {
  887. return $result;
  888. }
  889. } elseif ($route) {
  890. if ('__miss__' == $rule || '__auto__' == $rule) {
  891. // 指定特殊路由
  892. $var = trim($rule, '__');
  893. ${$var} = $item;
  894. continue;
  895. }
  896. if ($group) {
  897. $rule = $group . ($rule ? '/' . ltrim($rule, '/') : '');
  898. }
  899. self::setOption($option);
  900. if (isset($options['bind_model']) && isset($option['bind_model'])) {
  901. $option['bind_model'] = array_merge($options['bind_model'], $option['bind_model']);
  902. }
  903. $result = self::checkRule($rule, $route, $url, $pattern, $option, $depr);
  904. if (false !== $result) {
  905. return $result;
  906. }
  907. }
  908. }
  909. if (isset($auto)) {
  910. // 自动解析URL地址
  911. return self::parseUrl($auto['route'] . '/' . $url, $depr);
  912. } elseif (isset($miss)) {
  913. // 未匹配所有路由的路由规则处理
  914. return self::parseRule('', $miss['route'], $url, $miss['option']);
  915. }
  916. return false;
  917. }
  918. /**
  919. * 检测路由别名
  920. * @access private
  921. * @param Request $request
  922. * @param string $url URL地址
  923. * @param string $depr URL分隔符
  924. * @return mixed
  925. */
  926. private static function checkRouteAlias($request, $url, $depr)
  927. {
  928. $array = explode('|', $url);
  929. $alias = array_shift($array);
  930. $item = self::$rules['alias'][$alias];
  931. if (is_array($item)) {
  932. list($rule, $option) = $item;
  933. $action = $array[0];
  934. if (isset($option['allow']) && !in_array($action, explode(',', $option['allow']))) {
  935. // 允许操作
  936. return false;
  937. } elseif (isset($option['except']) && in_array($action, explode(',', $option['except']))) {
  938. // 排除操作
  939. return false;
  940. }
  941. if (isset($option['method'][$action])) {
  942. $option['method'] = $option['method'][$action];
  943. }
  944. } else {
  945. $rule = $item;
  946. }
  947. $bind = implode('|', $array);
  948. // 参数有效性检查
  949. if (isset($option) && !self::checkOption($option, $request)) {
  950. // 路由不匹配
  951. return false;
  952. } elseif (0 === strpos($rule, '\\')) {
  953. // 路由到类
  954. return self::bindToClass($bind, substr($rule, 1), $depr);
  955. } elseif (0 === strpos($rule, '@')) {
  956. // 路由到控制器类
  957. return self::bindToController($bind, substr($rule, 1), $depr);
  958. } else {
  959. // 路由到模块/控制器
  960. return self::bindToModule($bind, $rule, $depr);
  961. }
  962. }
  963. /**
  964. * 检测URL绑定
  965. * @access private
  966. * @param string $url URL地址
  967. * @param array $rules 路由规则
  968. * @param string $depr URL分隔符
  969. * @return mixed
  970. */
  971. private static function checkUrlBind(&$url, &$rules, $depr = '/')
  972. {
  973. if (!empty(self::$bind)) {
  974. $type = self::$bind['type'];
  975. $bind = self::$bind[$type];
  976. // 记录绑定信息
  977. App::$debug && Log::record('[ BIND ] ' . var_export($bind, true), 'info');
  978. // 如果有URL绑定 则进行绑定检测
  979. switch ($type) {
  980. case 'class':
  981. // 绑定到类
  982. return self::bindToClass($url, $bind, $depr);
  983. case 'controller':
  984. // 绑定到控制器类
  985. return self::bindToController($url, $bind, $depr);
  986. case 'namespace':
  987. // 绑定到命名空间
  988. return self::bindToNamespace($url, $bind, $depr);
  989. }
  990. }
  991. return false;
  992. }
  993. /**
  994. * 绑定到类
  995. * @access public
  996. * @param string $url URL地址
  997. * @param string $class 类名(带命名空间)
  998. * @param string $depr URL分隔符
  999. * @return array
  1000. */
  1001. public static function bindToClass($url, $class, $depr = '/')
  1002. {
  1003. $url = str_replace($depr, '|', $url);
  1004. $array = explode('|', $url, 2);
  1005. $action = !empty($array[0]) ? $array[0] : Config::get('default_action');
  1006. if (!empty($array[1])) {
  1007. self::parseUrlParams($array[1]);
  1008. }
  1009. return ['type' => 'method', 'method' => [$class, $action], 'var' => []];
  1010. }
  1011. /**
  1012. * 绑定到命名空间
  1013. * @access public
  1014. * @param string $url URL地址
  1015. * @param string $namespace 命名空间
  1016. * @param string $depr URL分隔符
  1017. * @return array
  1018. */
  1019. public static function bindToNamespace($url, $namespace, $depr = '/')
  1020. {
  1021. $url = str_replace($depr, '|', $url);
  1022. $array = explode('|', $url, 3);
  1023. $class = !empty($array[0]) ? $array[0] : Config::get('default_controller');
  1024. $method = !empty($array[1]) ? $array[1] : Config::get('default_action');
  1025. if (!empty($array[2])) {
  1026. self::parseUrlParams($array[2]);
  1027. }
  1028. return ['type' => 'method', 'method' => [$namespace . '\\' . Loader::parseName($class, 1), $method], 'var' => []];
  1029. }
  1030. /**
  1031. * 绑定到控制器类
  1032. * @access public
  1033. * @param string $url URL地址
  1034. * @param string $controller 控制器名 (支持带模块名 index/user )
  1035. * @param string $depr URL分隔符
  1036. * @return array
  1037. */
  1038. public static function bindToController($url, $controller, $depr = '/')
  1039. {
  1040. $url = str_replace($depr, '|', $url);
  1041. $array = explode('|', $url, 2);
  1042. $action = !empty($array[0]) ? $array[0] : Config::get('default_action');
  1043. if (!empty($array[1])) {
  1044. self::parseUrlParams($array[1]);
  1045. }
  1046. return ['type' => 'controller', 'controller' => $controller . '/' . $action, 'var' => []];
  1047. }
  1048. /**
  1049. * 绑定到模块/控制器
  1050. * @access public
  1051. * @param string $url URL地址
  1052. * @param string $controller 控制器类名(带命名空间)
  1053. * @param string $depr URL分隔符
  1054. * @return array
  1055. */
  1056. public static function bindToModule($url, $controller, $depr = '/')
  1057. {
  1058. $url = str_replace($depr, '|', $url);
  1059. $array = explode('|', $url, 2);
  1060. $action = !empty($array[0]) ? $array[0] : Config::get('default_action');
  1061. if (!empty($array[1])) {
  1062. self::parseUrlParams($array[1]);
  1063. }
  1064. return ['type' => 'module', 'module' => $controller . '/' . $action];
  1065. }
  1066. /**
  1067. * 路由参数有效性检查
  1068. * @access private
  1069. * @param array $option 路由参数
  1070. * @param Request $request Request对象
  1071. * @return bool
  1072. */
  1073. private static function checkOption($option, $request)
  1074. {
  1075. if ((isset($option['method']) && is_string($option['method']) && false === stripos($option['method'], $request->method()))
  1076. || (isset($option['ajax']) && $option['ajax'] && !$request->isAjax()) // Ajax检测
  1077. || (isset($option['ajax']) && !$option['ajax'] && $request->isAjax()) // 非Ajax检测
  1078. || (isset($option['pjax']) && $option['pjax'] && !$request->isPjax()) // Pjax检测
  1079. || (isset($option['pjax']) && !$option['pjax'] && $request->isPjax()) // 非Pjax检测
  1080. || (isset($option['ext']) && false === stripos('|' . $option['ext'] . '|', '|' . $request->ext() . '|')) // 伪静态后缀检测
  1081. || (isset($option['deny_ext']) && false !== stripos('|' . $option['deny_ext'] . '|', '|' . $request->ext() . '|'))
  1082. || (isset($option['domain']) && !in_array($option['domain'], [$_SERVER['HTTP_HOST'], self::$subDomain])) // 域名检测
  1083. || (isset($option['https']) && $option['https'] && !$request->isSsl()) // https检测
  1084. || (isset($option['https']) && !$option['https'] && $request->isSsl()) // https检测
  1085. || (!empty($option['before_behavior']) && false === Hook::exec($option['before_behavior'])) // 行为检测
  1086. || (!empty($option['callback']) && is_callable($option['callback']) && false === call_user_func($option['callback'])) // 自定义检测
  1087. ) {
  1088. return false;
  1089. }
  1090. return true;
  1091. }
  1092. /**
  1093. * 检测路由规则
  1094. * @access private
  1095. * @param string $rule 路由规则
  1096. * @param string $route 路由地址
  1097. * @param string $url URL地址
  1098. * @param array $pattern 变量规则
  1099. * @param array $option 路由参数
  1100. * @param string $depr URL分隔符(全局)
  1101. * @return array|false
  1102. */
  1103. private static function checkRule($rule, $route, $url, $pattern, $option, $depr)
  1104. {
  1105. // 检查完整规则定义
  1106. if (isset($pattern['__url__']) && !preg_match(0 === strpos($pattern['__url__'], '/') ? $pattern['__url__'] : '/^' . $pattern['__url__'] . '/', str_replace('|', $depr, $url))) {
  1107. return false;
  1108. }
  1109. // 检查路由的参数分隔符
  1110. if (isset($option['param_depr'])) {
  1111. $url = str_replace(['|', $option['param_depr']], [$depr, '|'], $url);
  1112. }
  1113. $len1 = substr_count($url, '|');
  1114. $len2 = substr_count($rule, '/');
  1115. // 多余参数是否合并
  1116. $merge = !empty($option['merge_extra_vars']);
  1117. if ($merge && $len1 > $len2) {
  1118. $url = str_replace('|', $depr, $url);
  1119. $url = implode('|', explode($depr, $url, $len2 + 1));
  1120. }
  1121. if ($len1 >= $len2 || strpos($rule, '[')) {
  1122. if (!empty($option['complete_match'])) {
  1123. // 完整匹配
  1124. if (!$merge && $len1 != $len2 && (false === strpos($rule, '[') || $len1 > $len2 || $len1 < $len2 - substr_count($rule, '['))) {
  1125. return false;
  1126. }
  1127. }
  1128. $pattern = array_merge(self::$rules['pattern'], $pattern);
  1129. if (false !== $match = self::match($url, $rule, $pattern)) {
  1130. // 匹配到路由规则
  1131. return self::parseRule($rule, $route, $url, $option, $match);
  1132. }
  1133. }
  1134. return false;
  1135. }
  1136. /**
  1137. * 解析模块的URL地址 [模块/控制器/操作?]参数1=值1&参数2=值2...
  1138. * @access public
  1139. * @param string $url URL地址
  1140. * @param string $depr URL分隔符
  1141. * @param bool $autoSearch 是否自动深度搜索控制器
  1142. * @return array
  1143. */
  1144. public static function parseUrl($url, $depr = '/', $autoSearch = false)
  1145. {
  1146. if (isset(self::$bind['module'])) {
  1147. $bind = str_replace('/', $depr, self::$bind['module']);
  1148. // 如果有模块/控制器绑定
  1149. $url = $bind . ('.' != substr($bind, -1) ? $depr : '') . ltrim($url, $depr);
  1150. }
  1151. $url = str_replace($depr, '|', $url);
  1152. list($path, $var) = self::parseUrlPath($url);
  1153. $route = [null, null, null];
  1154. if (isset($path)) {
  1155. // 解析模块
  1156. $module = Config::get('app_multi_module') ? array_shift($path) : null;
  1157. if ($autoSearch) {
  1158. // 自动搜索控制器
  1159. $dir = APP_PATH . ($module ? $module . DS : '') . Config::get('url_controller_layer');
  1160. $suffix = App::$suffix || Config::get('controller_suffix') ? ucfirst(Config::get('url_controller_layer')) : '';
  1161. $item = [];
  1162. $find = false;
  1163. foreach ($path as $val) {
  1164. $item[] = $val;
  1165. $file = $dir . DS . str_replace('.', DS, $val) . $suffix . EXT;
  1166. $file = pathinfo($file, PATHINFO_DIRNAME) . DS . Loader::parseName(pathinfo($file, PATHINFO_FILENAME), 1) . EXT;
  1167. if (is_file($file)) {
  1168. $find = true;
  1169. break;
  1170. } else {
  1171. $dir .= DS . Loader::parseName($val);
  1172. }
  1173. }
  1174. if ($find) {
  1175. $controller = implode('.', $item);
  1176. $path = array_slice($path, count($item));
  1177. } else {
  1178. $controller = array_shift($path);
  1179. }
  1180. } else {
  1181. // 解析控制器
  1182. $controller = !empty($path) ? array_shift($path) : null;
  1183. }
  1184. // 解析操作
  1185. $action = !empty($path) ? array_shift($path) : null;
  1186. // 解析额外参数
  1187. self::parseUrlParams(empty($path) ? '' : implode('|', $path));
  1188. // 封装路由
  1189. $route = [$module, $controller, $action];
  1190. // 检查地址是否被定义过路由
  1191. $name = strtolower($module . '/' . Loader::parseName($controller, 1) . '/' . $action);
  1192. $name2 = '';
  1193. if (empty($module) || isset($bind) && $module == $bind) {
  1194. $name2 = strtolower(Loader::parseName($controller, 1) . '/' . $action);
  1195. }
  1196. if (isset(self::$rules['name'][$name]) || isset(self::$rules['name'][$name2])) {
  1197. throw new HttpException(404, 'invalid request:' . str_replace('|', $depr, $url));
  1198. }
  1199. }
  1200. return ['type' => 'module', 'module' => $route];
  1201. }
  1202. /**
  1203. * 解析URL的pathinfo参数和变量
  1204. * @access private
  1205. * @param string $url URL地址
  1206. * @return array
  1207. */
  1208. private static function parseUrlPath($url)
  1209. {
  1210. // 分隔符替换 确保路由定义使用统一的分隔符
  1211. $url = str_replace('|', '/', $url);
  1212. $url = trim($url, '/');
  1213. $var = [];
  1214. if (false !== strpos($url, '?')) {
  1215. // [模块/控制器/操作?]参数1=值1&参数2=值2...
  1216. $info = parse_url($url);
  1217. $path = explode('/', $info['path']);
  1218. parse_str($info['query'], $var);
  1219. } elseif (strpos($url, '/')) {
  1220. // [模块/控制器/操作]
  1221. $path = explode('/', $url);
  1222. } else {
  1223. $path = [$url];
  1224. }
  1225. return [$path, $var];
  1226. }
  1227. /**
  1228. * 检测URL和规则路由是否匹配
  1229. * @access private
  1230. * @param string $url URL地址
  1231. * @param string $rule 路由规则
  1232. * @param array $pattern 变量规则
  1233. * @return array|false
  1234. */
  1235. private static function match($url, $rule, $pattern)
  1236. {
  1237. $m2 = explode('/', $rule);
  1238. $m1 = explode('|', $url);
  1239. $var = [];
  1240. foreach ($m2 as $key => $val) {
  1241. // val中定义了多个变量 <id><name>
  1242. if (false !== strpos($val, '<') && preg_match_all('/<(\w+(\??))>/', $val, $matches)) {
  1243. $value = [];
  1244. $replace = [];
  1245. foreach ($matches[1] as $name) {
  1246. if (strpos($name, '?')) {
  1247. $name = substr($name, 0, -1);
  1248. $replace[] = '(' . (isset($pattern[$name]) ? $pattern[$name] : '\w+') . ')?';
  1249. } else {
  1250. $replace[] = '(' . (isset($pattern[$name]) ? $pattern[$name] : '\w+') . ')';
  1251. }
  1252. $value[] = $name;
  1253. }
  1254. $val = str_replace($matches[0], $replace, $val);
  1255. if (preg_match('/^' . $val . '$/', isset($m1[$key]) ? $m1[$key] : '', $match)) {
  1256. array_shift($match);
  1257. foreach ($value as $k => $name) {
  1258. if (isset($match[$k])) {
  1259. $var[$name] = $match[$k];
  1260. }
  1261. }
  1262. continue;
  1263. } else {
  1264. return false;
  1265. }
  1266. }
  1267. if (0 === strpos($val, '[:')) {
  1268. // 可选参数
  1269. $val = substr($val, 1, -1);
  1270. $optional = true;
  1271. } else {
  1272. $optional = false;
  1273. }
  1274. if (0 === strpos($val, ':')) {
  1275. // URL变量
  1276. $name = substr($val, 1);
  1277. if (!$optional && !isset($m1[$key])) {
  1278. return false;
  1279. }
  1280. if (isset($m1[$key]) && isset($pattern[$name])) {
  1281. // 检查变量规则
  1282. if ($pattern[$name] instanceof \Closure) {
  1283. $result = call_user_func_array($pattern[$name], [$m1[$key]]);
  1284. if (false === $result) {
  1285. return false;
  1286. }
  1287. } elseif (!preg_match(0 === strpos($pattern[$name], '/') ? $pattern[$name] : '/^' . $pattern[$name] . '$/', $m1[$key])) {
  1288. return false;
  1289. }
  1290. }
  1291. $var[$name] = isset($m1[$key]) ? $m1[$key] : '';
  1292. } elseif (!isset($m1[$key]) || 0 !== strcasecmp($val, $m1[$key])) {
  1293. return false;
  1294. }
  1295. }
  1296. // 成功匹配后返回URL中的动态变量数组
  1297. return $var;
  1298. }
  1299. /**
  1300. * 解析规则路由
  1301. * @access private
  1302. * @param string $rule 路由规则
  1303. * @param string $route 路由地址
  1304. * @param string $pathinfo URL地址
  1305. * @param array $option 路由参数
  1306. * @param array $matches 匹配的变量
  1307. * @param bool $fromCache 通过缓存解析
  1308. * @return array
  1309. */
  1310. private static function parseRule($rule, $route, $pathinfo, $option = [], $matches = [], $fromCache = false)
  1311. {
  1312. $request = Request::instance();
  1313. //保存解析缓存
  1314. if (Config::get('route_check_cache') && !$fromCache) {
  1315. try {
  1316. $key = self::getCheckCacheKey($request);
  1317. Cache::tag('route_check')->set($key, [$rule, $route, $pathinfo, $option, $matches]);
  1318. } catch (\Exception $e) {
  1319. }
  1320. }
  1321. // 解析路由规则
  1322. if ($rule) {
  1323. $rule = explode('/', $rule);
  1324. // 获取URL地址中的参数
  1325. $paths = explode('|', $pathinfo);
  1326. foreach ($rule as $item) {
  1327. $fun = '';
  1328. if (0 === strpos($item, '[:')) {
  1329. $item = substr($item, 1, -1);
  1330. }
  1331. if (0 === strpos($item, ':')) {
  1332. $var = substr($item, 1);
  1333. $matches[$var] = array_shift($paths);
  1334. } else {
  1335. // 过滤URL中的静态变量
  1336. array_shift($paths);
  1337. }
  1338. }
  1339. } else {
  1340. $paths = explode('|', $pathinfo);
  1341. }
  1342. // 获取路由地址规则
  1343. if (is_string($route) && isset($option['prefix'])) {
  1344. // 路由地址前缀
  1345. $route = $option['prefix'] . $route;
  1346. }
  1347. // 替换路由地址中的变量
  1348. if (is_string($route) && !empty($matches)) {
  1349. foreach ($matches as $key => $val) {
  1350. if (false !== strpos($route, ':' . $key)) {
  1351. $route = str_replace(':' . $key, $val, $route);
  1352. }
  1353. }
  1354. }
  1355. // 绑定模型数据
  1356. if (isset($option['bind_model'])) {
  1357. $bind = [];
  1358. foreach ($option['bind_model'] as $key => $val) {
  1359. if ($val instanceof \Closure) {
  1360. $result = call_user_func_array($val, [$matches]);
  1361. } else {
  1362. if (is_array($val)) {
  1363. $fields = explode('&', $val[1]);
  1364. $model = $val[0];
  1365. $exception = isset($val[2]) ? $val[2] : true;
  1366. } else {
  1367. $fields = ['id'];
  1368. $model = $val;
  1369. $exception = true;
  1370. }
  1371. $where = [];
  1372. $match = true;
  1373. foreach ($fields as $field) {
  1374. if (!isset($matches[$field])) {
  1375. $match = false;
  1376. break;
  1377. } else {
  1378. $where[$field] = $matches[$field];
  1379. }
  1380. }
  1381. if ($match) {
  1382. $query = strpos($model, '\\') ? $model::where($where) : Loader::model($model)->where($where);
  1383. $result = $query->failException($exception)->find();
  1384. }
  1385. }
  1386. if (!empty($result)) {
  1387. $bind[$key] = $result;
  1388. }
  1389. }
  1390. $request->bind($bind);
  1391. }
  1392. if (!empty($option['response'])) {
  1393. Hook::add('response_send', $option['response']);
  1394. }
  1395. // 解析额外参数
  1396. self::parseUrlParams(empty($paths) ? '' : implode('|', $paths), $matches);
  1397. // 记录匹配的路由信息
  1398. $request->routeInfo(['rule' => $rule, 'route' => $route, 'option' => $option, 'var' => $matches]);
  1399. // 检测路由after行为
  1400. if (!empty($option['after_behavior'])) {
  1401. if ($option['after_behavior'] instanceof \Closure) {
  1402. $result = call_user_func_array($option['after_behavior'], []);
  1403. } else {
  1404. foreach ((array) $option['after_behavior'] as $behavior) {
  1405. $result = Hook::exec($behavior, '');
  1406. if (!is_null($result)) {
  1407. break;
  1408. }
  1409. }
  1410. }
  1411. // 路由规则重定向
  1412. if ($result instanceof Response) {
  1413. return ['type' => 'response', 'response' => $result];
  1414. } elseif (is_array($result)) {
  1415. return $result;
  1416. }
  1417. }
  1418. if ($route instanceof \Closure) {
  1419. // 执行闭包
  1420. $result = ['type' => 'function', 'function' => $route];
  1421. } elseif (0 === strpos($route, '/') || strpos($route, '://')) {
  1422. // 路由到重定向地址
  1423. $result = ['type' => 'redirect', 'url' => $route, 'status' => isset($option['status']) ? $option['status'] : 301];
  1424. } elseif (false !== strpos($route, '\\')) {
  1425. // 路由到方法
  1426. list($path, $var) = self::parseUrlPath($route);
  1427. $route = str_replace('/', '@', implode('/', $path));
  1428. $method = strpos($route, '@') ? explode('@', $route) : $route;
  1429. $result = ['type' => 'method', 'method' => $method, 'var' => $var];
  1430. } elseif (0 === strpos($route, '@')) {
  1431. // 路由到控制器
  1432. $route = substr($route, 1);
  1433. list($route, $var) = self::parseUrlPath($route);
  1434. $result = ['type' => 'controller', 'controller' => implode('/', $route), 'var' => $var];
  1435. $request->action(array_pop($route));
  1436. $request->controller($route ? array_pop($route) : Config::get('default_controller'));
  1437. $request->module($route ? array_pop($route) : Config::get('default_module'));
  1438. App::$modulePath = APP_PATH . (Config::get('app_multi_module') ? $request->module() . DS : '');
  1439. } else {
  1440. // 路由到模块/控制器/操作
  1441. $result = self::parseModule($route, isset($option['convert']) ? $option['convert'] : false);
  1442. }
  1443. // 开启请求缓存
  1444. if ($request->isGet() && isset($option['cache'])) {
  1445. $cache = $option['cache'];
  1446. if (is_array($cache)) {
  1447. list($key, $expire, $tag) = array_pad($cache, 3, null);
  1448. } else {
  1449. $key = str_replace('|', '/', $pathinfo);
  1450. $expire = $cache;
  1451. $tag = null;
  1452. }
  1453. $request->cache($key, $expire, $tag);
  1454. }
  1455. return $result;
  1456. }
  1457. /**
  1458. * 解析URL地址为 模块/控制器/操作
  1459. * @access private
  1460. * @param string $url URL地址
  1461. * @param bool $convert 是否自动转换URL地址
  1462. * @return array
  1463. */
  1464. private static function parseModule($url, $convert = false)
  1465. {
  1466. list($path, $var) = self::parseUrlPath($url);
  1467. $action = array_pop($path);
  1468. $controller = !empty($path) ? array_pop($path) : null;
  1469. $module = Config::get('app_multi_module') && !empty($path) ? array_pop($path) : null;
  1470. $method = Request::instance()->method();
  1471. if (Config::get('use_action_prefix') && !empty(self::$methodPrefix[$method])) {
  1472. // 操作方法前缀支持
  1473. $action = 0 !== strpos($action, self::$methodPrefix[$method]) ? self::$methodPrefix[$method] . $action : $action;
  1474. }
  1475. // 设置当前请求的路由变量
  1476. Request::instance()->route($var);
  1477. // 路由到模块/控制器/操作
  1478. return ['type' => 'module', 'module' => [$module, $controller, $action], 'convert' => $convert];
  1479. }
  1480. /**
  1481. * 解析URL地址中的参数Request对象
  1482. * @access private
  1483. * @param string $url 路由规则
  1484. * @param array $var 变量
  1485. * @return void
  1486. */
  1487. private static function parseUrlParams($url, &$var = [])
  1488. {
  1489. if ($url) {
  1490. if (Config::get('url_param_type')) {
  1491. $var += explode('|', $url);
  1492. } else {
  1493. preg_replace_callback('/(\w+)\|([^\|]+)/', function ($match) use (&$var) {
  1494. $var[$match[1]] = strip_tags($match[2]);
  1495. }, $url);
  1496. }
  1497. }
  1498. // 设置当前请求的参数
  1499. Request::instance()->route($var);
  1500. }
  1501. // 分析路由规则中的变量
  1502. private static function parseVar($rule)
  1503. {
  1504. // 提取路由规则中的变量
  1505. $var = [];
  1506. foreach (explode('/', $rule) as $val) {
  1507. $optional = false;
  1508. if (false !== strpos($val, '<') && preg_match_all('/<(\w+(\??))>/', $val, $matches)) {
  1509. foreach ($matches[1] as $name) {
  1510. if (strpos($name, '?')) {
  1511. $name = substr($name, 0, -1);
  1512. $optional = true;
  1513. } else {
  1514. $optional = false;
  1515. }
  1516. $var[$name] = $optional ? 2 : 1;
  1517. }
  1518. }
  1519. if (0 === strpos($val, '[:')) {
  1520. // 可选参数
  1521. $optional = true;
  1522. $val = substr($val, 1, -1);
  1523. }
  1524. if (0 === strpos($val, ':')) {
  1525. // URL变量
  1526. $name = substr($val, 1);
  1527. $var[$name] = $optional ? 2 : 1;
  1528. }
  1529. }
  1530. return $var;
  1531. }
  1532. /**
  1533. * 获取路由解析缓存的key
  1534. * @param Request $request
  1535. * @return string
  1536. */
  1537. private static function getCheckCacheKey(Request $request)
  1538. {
  1539. static $key;
  1540. if (empty($key)) {
  1541. if ($callback = Config::get('route_check_cache_key')) {
  1542. $key = call_user_func($callback, $request);
  1543. } else {
  1544. $key = "{$request->host(true)}|{$request->method()}|{$request->path()}";
  1545. }
  1546. }
  1547. return $key;
  1548. }
  1549. }