RuleGroup.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  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\route;
  12. use think\Container;
  13. use think\Exception;
  14. use think\Request;
  15. use think\Response;
  16. use think\Route;
  17. use think\route\dispatch\Response as ResponseDispatch;
  18. use think\route\dispatch\Url as UrlDispatch;
  19. class RuleGroup extends Rule
  20. {
  21. // 分组路由(包括子分组)
  22. protected $rules = [
  23. '*' => [],
  24. 'get' => [],
  25. 'post' => [],
  26. 'put' => [],
  27. 'patch' => [],
  28. 'delete' => [],
  29. 'head' => [],
  30. 'options' => [],
  31. ];
  32. // MISS路由
  33. protected $miss;
  34. // 自动路由
  35. protected $auto;
  36. // 完整名称
  37. protected $fullName;
  38. // 所在域名
  39. protected $domain;
  40. /**
  41. * 架构函数
  42. * @access public
  43. * @param Route $router 路由对象
  44. * @param RuleGroup $parent 上级对象
  45. * @param string $name 分组名称
  46. * @param mixed $rule 分组路由
  47. * @param array $option 路由参数
  48. * @param array $pattern 变量规则
  49. */
  50. public function __construct(Route $router, RuleGroup $parent = null, $name = '', $rule = [], $option = [], $pattern = [])
  51. {
  52. $this->router = $router;
  53. $this->parent = $parent;
  54. $this->rule = $rule;
  55. $this->name = trim($name, '/');
  56. $this->option = $option;
  57. $this->pattern = $pattern;
  58. $this->setFullName();
  59. if ($this->parent) {
  60. $this->domain = $this->parent->getDomain();
  61. $this->parent->addRuleItem($this);
  62. }
  63. if (!empty($option['cross_domain'])) {
  64. $this->router->setCrossDomainRule($this);
  65. }
  66. if ($router->isTest()) {
  67. $this->lazy(false);
  68. }
  69. }
  70. /**
  71. * 设置分组的路由规则
  72. * @access public
  73. * @return void
  74. */
  75. protected function setFullName()
  76. {
  77. if (false !== strpos($this->name, ':')) {
  78. $this->name = preg_replace(['/\[\:(\w+)\]/', '/\:(\w+)/'], ['<\1?>', '<\1>'], $this->name);
  79. }
  80. if ($this->parent && $this->parent->getFullName()) {
  81. $this->fullName = $this->parent->getFullName() . ($this->name ? '/' . $this->name : '');
  82. } else {
  83. $this->fullName = $this->name;
  84. }
  85. }
  86. /**
  87. * 获取所属域名
  88. * @access public
  89. * @return string
  90. */
  91. public function getDomain()
  92. {
  93. return $this->domain;
  94. }
  95. /**
  96. * 检测分组路由
  97. * @access public
  98. * @param Request $request 请求对象
  99. * @param string $url 访问地址
  100. * @param bool $completeMatch 路由是否完全匹配
  101. * @return Dispatch|false
  102. */
  103. public function check($request, $url, $completeMatch = false)
  104. {
  105. // 跨域OPTIONS请求
  106. if ($dispatch = $this->checkCrossDomain($request)) {
  107. return $dispatch;
  108. }
  109. // 检查分组有效性
  110. if (!$this->checkOption($this->option, $request) || !$this->checkUrl($url)) {
  111. return false;
  112. }
  113. // 检查前置行为
  114. if (isset($this->option['before'])) {
  115. if (false === $this->checkBefore($this->option['before'])) {
  116. return false;
  117. }
  118. unset($this->option['before']);
  119. }
  120. // 解析分组路由
  121. if ($this instanceof Resource) {
  122. $this->buildResourceRule();
  123. } elseif ($this->rule) {
  124. if ($this->rule instanceof Response) {
  125. return new ResponseDispatch($request, $this, $this->rule);
  126. }
  127. $this->parseGroupRule($this->rule);
  128. }
  129. // 获取当前路由规则
  130. $method = strtolower($request->method());
  131. $rules = $this->getMethodRules($method);
  132. if ($this->parent) {
  133. // 合并分组参数
  134. $this->mergeGroupOptions();
  135. // 合并分组变量规则
  136. $this->pattern = array_merge($this->parent->getPattern(), $this->pattern);
  137. }
  138. if (isset($this->option['complete_match'])) {
  139. $completeMatch = $this->option['complete_match'];
  140. }
  141. if (!empty($this->option['merge_rule_regex'])) {
  142. // 合并路由正则规则进行路由匹配检查
  143. $result = $this->checkMergeRuleRegex($request, $rules, $url, $completeMatch);
  144. if (false !== $result) {
  145. return $result;
  146. }
  147. }
  148. // 检查分组路由
  149. foreach ($rules as $key => $item) {
  150. $result = $item->check($request, $url, $completeMatch);
  151. if (false !== $result) {
  152. return $result;
  153. }
  154. }
  155. if ($this->auto) {
  156. // 自动解析URL地址
  157. $result = new UrlDispatch($request, $this, $this->auto . '/' . $url, ['auto_search' => false]);
  158. } elseif ($this->miss && in_array($this->miss->getMethod(), ['*', $method])) {
  159. // 未匹配所有路由的路由规则处理
  160. $result = $this->miss->parseRule($request, '', $this->miss->getRoute(), $url, $this->miss->mergeGroupOptions());
  161. } else {
  162. $result = false;
  163. }
  164. return $result;
  165. }
  166. /**
  167. * 获取当前请求的路由规则(包括子分组、资源路由)
  168. * @access protected
  169. * @param string $method
  170. * @return array
  171. */
  172. protected function getMethodRules($method)
  173. {
  174. return array_merge($this->rules[$method], $this->rules['*']);
  175. }
  176. /**
  177. * 分组URL匹配检查
  178. * @access protected
  179. * @param string $url
  180. * @return bool
  181. */
  182. protected function checkUrl($url)
  183. {
  184. if ($this->fullName) {
  185. $pos = strpos($this->fullName, '<');
  186. if (false !== $pos) {
  187. $str = substr($this->fullName, 0, $pos);
  188. } else {
  189. $str = $this->fullName;
  190. }
  191. if ($str && 0 !== stripos(str_replace('|', '/', $url), $str)) {
  192. return false;
  193. }
  194. }
  195. return true;
  196. }
  197. /**
  198. * 延迟解析分组的路由规则
  199. * @access public
  200. * @param bool $lazy 路由是否延迟解析
  201. * @return $this
  202. */
  203. public function lazy($lazy = true)
  204. {
  205. if (!$lazy) {
  206. $this->parseGroupRule($this->rule);
  207. $this->rule = null;
  208. }
  209. return $this;
  210. }
  211. /**
  212. * 解析分组和域名的路由规则及绑定
  213. * @access public
  214. * @param mixed $rule 路由规则
  215. * @return void
  216. */
  217. public function parseGroupRule($rule)
  218. {
  219. $origin = $this->router->getGroup();
  220. $this->router->setGroup($this);
  221. if ($rule instanceof \Closure) {
  222. Container::getInstance()->invokeFunction($rule);
  223. } elseif (is_array($rule)) {
  224. $this->addRules($rule);
  225. } elseif (is_string($rule) && $rule) {
  226. $this->router->bind($rule, $this->domain);
  227. }
  228. $this->router->setGroup($origin);
  229. }
  230. /**
  231. * 检测分组路由
  232. * @access public
  233. * @param Request $request 请求对象
  234. * @param array $rules 路由规则
  235. * @param string $url 访问地址
  236. * @param bool $completeMatch 路由是否完全匹配
  237. * @return Dispatch|false
  238. */
  239. protected function checkMergeRuleRegex($request, &$rules, $url, $completeMatch)
  240. {
  241. $depr = $this->router->config('pathinfo_depr');
  242. $url = $depr . str_replace('|', $depr, $url);
  243. foreach ($rules as $key => $item) {
  244. if ($item instanceof RuleItem) {
  245. $rule = $depr . str_replace('/', $depr, $item->getRule());
  246. if ($depr == $rule && $depr != $url) {
  247. unset($rules[$key]);
  248. continue;
  249. }
  250. $complete = null !== $item->getOption('complete_match') ? $item->getOption('complete_match') : $completeMatch;
  251. if (false === strpos($rule, '<')) {
  252. if (0 === strcasecmp($rule, $url) || (!$complete && 0 === strncasecmp($rule, $url, strlen($rule)))) {
  253. return $item->checkRule($request, $url, []);
  254. }
  255. unset($rules[$key]);
  256. continue;
  257. }
  258. $slash = preg_quote('/-' . $depr, '/');
  259. if ($matchRule = preg_split('/[' . $slash . ']<\w+\??>/', $rule, 2)) {
  260. if ($matchRule[0] && 0 !== strncasecmp($rule, $url, strlen($matchRule[0]))) {
  261. unset($rules[$key]);
  262. continue;
  263. }
  264. }
  265. if (preg_match_all('/[' . $slash . ']?<?\w+\??>?/', $rule, $matches)) {
  266. unset($rules[$key]);
  267. $pattern = array_merge($this->getPattern(), $item->getPattern());
  268. $option = array_merge($this->getOption(), $item->getOption());
  269. $regex[$key] = $this->buildRuleRegex($rule, $matches[0], $pattern, $option, $complete, '_THINK_' . $key);
  270. $items[$key] = $item;
  271. }
  272. }
  273. }
  274. if (empty($regex)) {
  275. return false;
  276. }
  277. try {
  278. $result = preg_match('/^(?:' . implode('|', $regex) . ')/u', $url, $match);
  279. } catch (\Exception $e) {
  280. throw new Exception('route pattern error');
  281. }
  282. if ($result) {
  283. $var = [];
  284. foreach ($match as $key => $val) {
  285. if (is_string($key) && '' !== $val) {
  286. list($name, $pos) = explode('_THINK_', $key);
  287. $var[$name] = $val;
  288. }
  289. }
  290. if (!isset($pos)) {
  291. foreach ($regex as $key => $item) {
  292. if (0 === strpos(str_replace(['\/', '\-', '\\' . $depr], ['/', '-', $depr], $item), $match[0])) {
  293. $pos = $key;
  294. break;
  295. }
  296. }
  297. }
  298. $rule = $items[$pos]->getRule();
  299. $array = $this->router->getRule($rule);
  300. foreach ($array as $item) {
  301. if (in_array($item->getMethod(), ['*', strtolower($request->method())])) {
  302. $result = $item->checkRule($request, $url, $var);
  303. if (false !== $result) {
  304. return $result;
  305. }
  306. }
  307. }
  308. }
  309. return false;
  310. }
  311. /**
  312. * 获取分组的MISS路由
  313. * @access public
  314. * @return RuleItem|null
  315. */
  316. public function getMissRule()
  317. {
  318. return $this->miss;
  319. }
  320. /**
  321. * 获取分组的自动路由
  322. * @access public
  323. * @return string
  324. */
  325. public function getAutoRule()
  326. {
  327. return $this->auto;
  328. }
  329. /**
  330. * 注册自动路由
  331. * @access public
  332. * @param string $route 路由规则
  333. * @return void
  334. */
  335. public function addAutoRule($route)
  336. {
  337. $this->auto = $route;
  338. }
  339. /**
  340. * 注册MISS路由
  341. * @access public
  342. * @param string $route 路由地址
  343. * @param string $method 请求类型
  344. * @param array $option 路由参数
  345. * @return RuleItem
  346. */
  347. public function addMissRule($route, $method = '*', $option = [])
  348. {
  349. // 创建路由规则实例
  350. $ruleItem = new RuleItem($this->router, $this, null, '', $route, strtolower($method), $option);
  351. $this->miss = $ruleItem;
  352. return $ruleItem;
  353. }
  354. /**
  355. * 添加分组下的路由规则或者子分组
  356. * @access public
  357. * @param string $rule 路由规则
  358. * @param string $route 路由地址
  359. * @param string $method 请求类型
  360. * @param array $option 路由参数
  361. * @param array $pattern 变量规则
  362. * @return $this
  363. */
  364. public function addRule($rule, $route, $method = '*', $option = [], $pattern = [])
  365. {
  366. // 读取路由标识
  367. if (is_array($rule)) {
  368. $name = $rule[0];
  369. $rule = $rule[1];
  370. } elseif (is_string($route)) {
  371. $name = $route;
  372. } else {
  373. $name = null;
  374. }
  375. $method = strtolower($method);
  376. if ('/' === $rule || '' === $rule) {
  377. // 首页自动完整匹配
  378. $rule .= '$';
  379. }
  380. // 创建路由规则实例
  381. $ruleItem = new RuleItem($this->router, $this, $name, $rule, $route, $method, $option, $pattern);
  382. if (!empty($option['cross_domain'])) {
  383. $this->router->setCrossDomainRule($ruleItem, $method);
  384. }
  385. $this->addRuleItem($ruleItem, $method);
  386. return $ruleItem;
  387. }
  388. /**
  389. * 批量注册路由规则
  390. * @access public
  391. * @param array $rules 路由规则
  392. * @param string $method 请求类型
  393. * @param array $option 路由参数
  394. * @param array $pattern 变量规则
  395. * @return void
  396. */
  397. public function addRules($rules, $method = '*', $option = [], $pattern = [])
  398. {
  399. foreach ($rules as $key => $val) {
  400. if (is_numeric($key)) {
  401. $key = array_shift($val);
  402. }
  403. if (is_array($val)) {
  404. $route = array_shift($val);
  405. $option = $val ? array_shift($val) : [];
  406. $pattern = $val ? array_shift($val) : [];
  407. } else {
  408. $route = $val;
  409. }
  410. $this->addRule($key, $route, $method, $option, $pattern);
  411. }
  412. }
  413. public function addRuleItem($rule, $method = '*')
  414. {
  415. if (strpos($method, '|')) {
  416. $rule->method($method);
  417. $method = '*';
  418. }
  419. $this->rules[$method][] = $rule;
  420. return $this;
  421. }
  422. /**
  423. * 设置分组的路由前缀
  424. * @access public
  425. * @param string $prefix
  426. * @return $this
  427. */
  428. public function prefix($prefix)
  429. {
  430. if ($this->parent && $this->parent->getOption('prefix')) {
  431. $prefix = $this->parent->getOption('prefix') . $prefix;
  432. }
  433. return $this->option('prefix', $prefix);
  434. }
  435. /**
  436. * 设置资源允许
  437. * @access public
  438. * @param array $only
  439. * @return $this
  440. */
  441. public function only($only)
  442. {
  443. return $this->option('only', $only);
  444. }
  445. /**
  446. * 设置资源排除
  447. * @access public
  448. * @param array $except
  449. * @return $this
  450. */
  451. public function except($except)
  452. {
  453. return $this->option('except', $except);
  454. }
  455. /**
  456. * 设置资源路由的变量
  457. * @access public
  458. * @param array $vars
  459. * @return $this
  460. */
  461. public function vars($vars)
  462. {
  463. return $this->option('var', $vars);
  464. }
  465. /**
  466. * 合并分组的路由规则正则
  467. * @access public
  468. * @param bool $merge
  469. * @return $this
  470. */
  471. public function mergeRuleRegex($merge = true)
  472. {
  473. return $this->option('merge_rule_regex', $merge);
  474. }
  475. /**
  476. * 获取完整分组Name
  477. * @access public
  478. * @return string
  479. */
  480. public function getFullName()
  481. {
  482. return $this->fullName;
  483. }
  484. /**
  485. * 获取分组的路由规则
  486. * @access public
  487. * @param string $method
  488. * @return array
  489. */
  490. public function getRules($method = '')
  491. {
  492. if ('' === $method) {
  493. return $this->rules;
  494. }
  495. return isset($this->rules[strtolower($method)]) ? $this->rules[strtolower($method)] : [];
  496. }
  497. /**
  498. * 清空分组下的路由规则
  499. * @access public
  500. * @return void
  501. */
  502. public function clear()
  503. {
  504. $this->rules = [
  505. '*' => [],
  506. 'get' => [],
  507. 'post' => [],
  508. 'put' => [],
  509. 'patch' => [],
  510. 'delete' => [],
  511. 'head' => [],
  512. 'options' => [],
  513. ];
  514. }
  515. }