RuleGroup.php 15 KB

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