RuleGroup.php 16 KB

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