Route.php 58 KB

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