Rule.php 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130
  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\Request;
  14. use think\Response;
  15. use think\route\dispatch\Callback as CallbackDispatch;
  16. use think\route\dispatch\Controller as ControllerDispatch;
  17. use think\route\dispatch\Module as ModuleDispatch;
  18. use think\route\dispatch\Redirect as RedirectDispatch;
  19. use think\route\dispatch\Response as ResponseDispatch;
  20. use think\route\dispatch\View as ViewDispatch;
  21. abstract class Rule
  22. {
  23. /**
  24. * 路由标识
  25. * @var string
  26. */
  27. protected $name;
  28. /**
  29. * 路由对象
  30. * @var Route
  31. */
  32. protected $router;
  33. /**
  34. * 路由所属分组
  35. * @var RuleGroup
  36. */
  37. protected $parent;
  38. /**
  39. * 路由规则
  40. * @var mixed
  41. */
  42. protected $rule;
  43. /**
  44. * 路由地址
  45. * @var string|\Closure
  46. */
  47. protected $route;
  48. /**
  49. * 请求类型
  50. * @var string
  51. */
  52. protected $method;
  53. /**
  54. * 路由变量
  55. * @var array
  56. */
  57. protected $vars = [];
  58. /**
  59. * 路由参数
  60. * @var array
  61. */
  62. protected $option = [];
  63. /**
  64. * 路由变量规则
  65. * @var array
  66. */
  67. protected $pattern = [];
  68. /**
  69. * 需要和分组合并的路由参数
  70. * @var array
  71. */
  72. protected $mergeOptions = ['after', 'model', 'header', 'response', 'append', 'middleware'];
  73. /**
  74. * 是否需要后置操作
  75. * @var bool
  76. */
  77. protected $doAfter;
  78. /**
  79. * 是否锁定参数
  80. * @var bool
  81. */
  82. protected $lockOption = false;
  83. abstract public function check($request, $url, $completeMatch = false);
  84. /**
  85. * 获取Name
  86. * @access public
  87. * @return string
  88. */
  89. public function getName()
  90. {
  91. return $this->name;
  92. }
  93. /**
  94. * 获取当前路由规则
  95. * @access public
  96. * @return string
  97. */
  98. public function getRule()
  99. {
  100. return $this->rule;
  101. }
  102. /**
  103. * 获取当前路由地址
  104. * @access public
  105. * @return mixed
  106. */
  107. public function getRoute()
  108. {
  109. return $this->route;
  110. }
  111. /**
  112. * 获取当前路由的请求类型
  113. * @access public
  114. * @return string
  115. */
  116. public function getMethod()
  117. {
  118. return strtolower($this->method);
  119. }
  120. /**
  121. * 获取当前路由的变量
  122. * @access public
  123. * @return array
  124. */
  125. public function getVars()
  126. {
  127. return $this->vars;
  128. }
  129. /**
  130. * 获取路由对象
  131. * @access public
  132. * @return Route
  133. */
  134. public function getRouter()
  135. {
  136. return $this->router;
  137. }
  138. /**
  139. * 路由是否有后置操作
  140. * @access public
  141. * @return bool
  142. */
  143. public function doAfter()
  144. {
  145. return $this->doAfter;
  146. }
  147. /**
  148. * 获取路由分组
  149. * @access public
  150. * @return RuleGroup|null
  151. */
  152. public function getParent()
  153. {
  154. return $this->parent;
  155. }
  156. /**
  157. * 获取路由所在域名
  158. * @access public
  159. * @return string
  160. */
  161. public function getDomain()
  162. {
  163. return $this->parent->getDomain();
  164. }
  165. /**
  166. * 获取变量规则定义
  167. * @access public
  168. * @param string $name 变量名
  169. * @return mixed
  170. */
  171. public function getPattern($name = '')
  172. {
  173. if ('' === $name) {
  174. return $this->pattern;
  175. }
  176. return isset($this->pattern[$name]) ? $this->pattern[$name] : null;
  177. }
  178. /**
  179. * 获取路由参数
  180. * @access public
  181. * @param string $name 变量名
  182. * @return mixed
  183. */
  184. public function getConfig($name = '')
  185. {
  186. return $this->router->config($name);
  187. }
  188. /**
  189. * 获取路由参数定义
  190. * @access public
  191. * @param string $name 参数名
  192. * @return mixed
  193. */
  194. public function getOption($name = '')
  195. {
  196. if ('' === $name) {
  197. return $this->option;
  198. }
  199. return isset($this->option[$name]) ? $this->option[$name] : null;
  200. }
  201. /**
  202. * 注册路由参数
  203. * @access public
  204. * @param string|array $name 参数名
  205. * @param mixed $value 值
  206. * @return $this
  207. */
  208. public function option($name, $value = '')
  209. {
  210. if (is_array($name)) {
  211. $this->option = array_merge($this->option, $name);
  212. } else {
  213. $this->option[$name] = $value;
  214. }
  215. return $this;
  216. }
  217. /**
  218. * 注册变量规则
  219. * @access public
  220. * @param string|array $name 变量名
  221. * @param string $rule 变量规则
  222. * @return $this
  223. */
  224. public function pattern($name, $rule = '')
  225. {
  226. if (is_array($name)) {
  227. $this->pattern = array_merge($this->pattern, $name);
  228. } else {
  229. $this->pattern[$name] = $rule;
  230. }
  231. return $this;
  232. }
  233. /**
  234. * 设置标识
  235. * @access public
  236. * @param string $name 标识名
  237. * @return $this
  238. */
  239. public function name($name)
  240. {
  241. $this->name = $name;
  242. return $this;
  243. }
  244. /**
  245. * 设置变量
  246. * @access public
  247. * @param array $vars 变量
  248. * @return $this
  249. */
  250. public function vars($vars)
  251. {
  252. $this->vars = $vars;
  253. return $this;
  254. }
  255. /**
  256. * 设置路由请求类型
  257. * @access public
  258. * @param string $method
  259. * @return $this
  260. */
  261. public function method($method)
  262. {
  263. return $this->option('method', strtolower($method));
  264. }
  265. /**
  266. * 设置路由前置行为
  267. * @access public
  268. * @param array|\Closure $before
  269. * @return $this
  270. */
  271. public function before($before)
  272. {
  273. return $this->option('before', $before);
  274. }
  275. /**
  276. * 设置路由后置行为
  277. * @access public
  278. * @param array|\Closure $after
  279. * @return $this
  280. */
  281. public function after($after)
  282. {
  283. return $this->option('after', $after);
  284. }
  285. /**
  286. * 检查后缀
  287. * @access public
  288. * @param string $ext
  289. * @return $this
  290. */
  291. public function ext($ext = '')
  292. {
  293. return $this->option('ext', $ext);
  294. }
  295. /**
  296. * 检查禁止后缀
  297. * @access public
  298. * @param string $ext
  299. * @return $this
  300. */
  301. public function denyExt($ext = '')
  302. {
  303. return $this->option('deny_ext', $ext);
  304. }
  305. /**
  306. * 检查域名
  307. * @access public
  308. * @param string $domain
  309. * @return $this
  310. */
  311. public function domain($domain)
  312. {
  313. return $this->option('domain', $domain);
  314. }
  315. /**
  316. * 设置参数过滤检查
  317. * @access public
  318. * @param string|array $name
  319. * @param mixed $value
  320. * @return $this
  321. */
  322. public function filter($name, $value = null)
  323. {
  324. if (is_array($name)) {
  325. $this->option['filter'] = $name;
  326. } else {
  327. $this->option['filter'][$name] = $value;
  328. }
  329. return $this;
  330. }
  331. /**
  332. * 绑定模型
  333. * @access public
  334. * @param array|string $var 路由变量名 多个使用 & 分割
  335. * @param string|\Closure $model 绑定模型类
  336. * @param bool $exception 是否抛出异常
  337. * @return $this
  338. */
  339. public function model($var, $model = null, $exception = true)
  340. {
  341. if ($var instanceof \Closure) {
  342. $this->option['model'][] = $var;
  343. } elseif (is_array($var)) {
  344. $this->option['model'] = $var;
  345. } elseif (is_null($model)) {
  346. $this->option['model']['id'] = [$var, true];
  347. } else {
  348. $this->option['model'][$var] = [$model, $exception];
  349. }
  350. return $this;
  351. }
  352. /**
  353. * 附加路由隐式参数
  354. * @access public
  355. * @param array $append
  356. * @return $this
  357. */
  358. public function append(array $append = [])
  359. {
  360. if (isset($this->option['append'])) {
  361. $this->option['append'] = array_merge($this->option['append'], $append);
  362. } else {
  363. $this->option['append'] = $append;
  364. }
  365. return $this;
  366. }
  367. /**
  368. * 绑定验证
  369. * @access public
  370. * @param mixed $validate 验证器类
  371. * @param string $scene 验证场景
  372. * @param array $message 验证提示
  373. * @param bool $batch 批量验证
  374. * @return $this
  375. */
  376. public function validate($validate, $scene = null, $message = [], $batch = false)
  377. {
  378. $this->option['validate'] = [$validate, $scene, $message, $batch];
  379. return $this;
  380. }
  381. /**
  382. * 绑定Response对象
  383. * @access public
  384. * @param mixed $response
  385. * @return $this
  386. */
  387. public function response($response)
  388. {
  389. $this->option['response'][] = $response;
  390. return $this;
  391. }
  392. /**
  393. * 设置Response Header信息
  394. * @access public
  395. * @param string|array $name 参数名
  396. * @param string $value 参数值
  397. * @return $this
  398. */
  399. public function header($header, $value = null)
  400. {
  401. if (is_array($header)) {
  402. $this->option['header'] = $header;
  403. } else {
  404. $this->option['header'][$header] = $value;
  405. }
  406. return $this;
  407. }
  408. /**
  409. * 指定路由中间件
  410. * @access public
  411. * @param string|array|\Closure $middleware
  412. * @param mixed $param
  413. * @return $this
  414. */
  415. public function middleware($middleware, $param = null)
  416. {
  417. if (is_null($param) && is_array($middleware)) {
  418. $this->option['middleware'] = $middleware;
  419. } else {
  420. foreach ((array) $middleware as $item) {
  421. $this->option['middleware'][] = [$item, $param];
  422. }
  423. }
  424. return $this;
  425. }
  426. /**
  427. * 设置路由缓存
  428. * @access public
  429. * @param array|string $cache
  430. * @return $this
  431. */
  432. public function cache($cache)
  433. {
  434. return $this->option('cache', $cache);
  435. }
  436. /**
  437. * 检查URL分隔符
  438. * @access public
  439. * @param bool $depr
  440. * @return $this
  441. */
  442. public function depr($depr)
  443. {
  444. return $this->option('param_depr', $depr);
  445. }
  446. /**
  447. * 是否合并额外参数
  448. * @access public
  449. * @param bool $merge
  450. * @return $this
  451. */
  452. public function mergeExtraVars($merge = true)
  453. {
  454. return $this->option('merge_extra_vars', $merge);
  455. }
  456. /**
  457. * 设置需要合并的路由参数
  458. * @access public
  459. * @param array $option
  460. * @return $this
  461. */
  462. public function mergeOptions($option = [])
  463. {
  464. $this->mergeOptions = array_merge($this->mergeOptions, $option);
  465. return $this;
  466. }
  467. /**
  468. * 检查是否为HTTPS请求
  469. * @access public
  470. * @param bool $https
  471. * @return $this
  472. */
  473. public function https($https = true)
  474. {
  475. return $this->option('https', $https);
  476. }
  477. /**
  478. * 检查是否为AJAX请求
  479. * @access public
  480. * @param bool $ajax
  481. * @return $this
  482. */
  483. public function ajax($ajax = true)
  484. {
  485. return $this->option('ajax', $ajax);
  486. }
  487. /**
  488. * 检查是否为PJAX请求
  489. * @access public
  490. * @param bool $pjax
  491. * @return $this
  492. */
  493. public function pjax($pjax = true)
  494. {
  495. return $this->option('pjax', $pjax);
  496. }
  497. /**
  498. * 检查是否为手机访问
  499. * @access public
  500. * @param bool $mobile
  501. * @return $this
  502. */
  503. public function mobile($mobile = true)
  504. {
  505. return $this->option('mobile', $mobile);
  506. }
  507. /**
  508. * 当前路由到一个模板地址 当使用数组的时候可以传入模板变量
  509. * @access public
  510. * @param bool|array $view
  511. * @return $this
  512. */
  513. public function view($view = true)
  514. {
  515. return $this->option('view', $view);
  516. }
  517. /**
  518. * 当前路由为重定向
  519. * @access public
  520. * @param bool $redirect 是否为重定向
  521. * @return $this
  522. */
  523. public function redirect($redirect = true)
  524. {
  525. return $this->option('redirect', $redirect);
  526. }
  527. /**
  528. * 设置路由完整匹配
  529. * @access public
  530. * @param bool $match
  531. * @return $this
  532. */
  533. public function completeMatch($match = true)
  534. {
  535. return $this->option('complete_match', $match);
  536. }
  537. /**
  538. * 是否去除URL最后的斜线
  539. * @access public
  540. * @param bool $remove
  541. * @return $this
  542. */
  543. public function removeSlash($remove = true)
  544. {
  545. return $this->option('remove_slash', $remove);
  546. }
  547. /**
  548. * 设置是否允许跨域
  549. * @access public
  550. * @param bool $allow
  551. * @param array $header
  552. * @return $this
  553. */
  554. public function allowCrossDomain($allow = true, $header = [])
  555. {
  556. if (!empty($header)) {
  557. $this->header($header);
  558. }
  559. if ($allow && $this->parent) {
  560. $this->parent->addRuleItem($this, 'options');
  561. }
  562. return $this->option('cross_domain', $allow);
  563. }
  564. /**
  565. * 检查OPTIONS请求
  566. * @access public
  567. * @param Request $request
  568. * @return Dispatch|void
  569. */
  570. protected function checkCrossDomain($request)
  571. {
  572. if (!empty($this->option['cross_domain'])) {
  573. $header = [
  574. 'Access-Control-Allow-Credentials' => 'true',
  575. 'Access-Control-Allow-Methods' => 'GET, POST, PATCH, PUT, DELETE',
  576. 'Access-Control-Allow-Headers' => 'Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-Requested-With',
  577. ];
  578. if (!empty($this->option['header'])) {
  579. $header = array_merge($header, $this->option['header']);
  580. }
  581. if (!isset($header['Access-Control-Allow-Origin'])) {
  582. $httpOrigin = $request->header('origin');
  583. if ($httpOrigin && strpos(config('cookie.domain'), $httpOrigin)) {
  584. $header['Access-Control-Allow-Origin'] = $httpOrigin;
  585. } else {
  586. $header['Access-Control-Allow-Origin'] = '*';
  587. }
  588. }
  589. $this->option['header'] = $header;
  590. if ($request->method(true) == 'OPTIONS') {
  591. return new ResponseDispatch($request, $this, Response::create()->code(204)->header($header));
  592. }
  593. }
  594. }
  595. /**
  596. * 设置路由规则全局有效
  597. * @access public
  598. * @return $this
  599. */
  600. public function crossDomainRule()
  601. {
  602. if ($this instanceof RuleGroup) {
  603. $method = '*';
  604. } else {
  605. $method = $this->method;
  606. }
  607. $this->router->setCrossDomainRule($this, $method);
  608. return $this;
  609. }
  610. /**
  611. * 合并分组参数
  612. * @access public
  613. * @return array
  614. */
  615. public function mergeGroupOptions()
  616. {
  617. if (!$this->lockOption) {
  618. $parentOption = $this->parent->getOption();
  619. // 合并分组参数
  620. foreach ($this->mergeOptions as $item) {
  621. if (isset($parentOption[$item]) && isset($this->option[$item])) {
  622. $this->option[$item] = array_merge($parentOption[$item], $this->option[$item]);
  623. }
  624. }
  625. $this->option = array_merge($parentOption, $this->option);
  626. $this->lockOption = true;
  627. }
  628. return $this->option;
  629. }
  630. /**
  631. * 解析匹配到的规则路由
  632. * @access public
  633. * @param Request $request 请求对象
  634. * @param string $rule 路由规则
  635. * @param string $route 路由地址
  636. * @param string $url URL地址
  637. * @param array $option 路由参数
  638. * @param array $matches 匹配的变量
  639. * @return Dispatch
  640. */
  641. public function parseRule($request, $rule, $route, $url, $option = [], $matches = [])
  642. {
  643. if (is_string($route) && isset($option['prefix'])) {
  644. // 路由地址前缀
  645. $route = $option['prefix'] . $route;
  646. }
  647. // 替换路由地址中的变量
  648. if (is_string($route) && !empty($matches)) {
  649. $search = $replace = [];
  650. foreach ($matches as $key => $value) {
  651. $search[] = '<' . $key . '>';
  652. $replace[] = $value;
  653. $search[] = ':' . $key;
  654. $replace[] = $value;
  655. }
  656. $route = str_replace($search, $replace, $route);
  657. }
  658. // 解析额外参数
  659. $count = substr_count($rule, '/');
  660. $url = array_slice(explode('|', $url), $count + 1);
  661. $this->parseUrlParams($request, implode('|', $url), $matches);
  662. $this->vars = $matches;
  663. $this->option = $option;
  664. $this->doAfter = true;
  665. // 发起路由调度
  666. return $this->dispatch($request, $route, $option);
  667. }
  668. /**
  669. * 检查路由前置行为
  670. * @access protected
  671. * @param mixed $before 前置行为
  672. * @return mixed
  673. */
  674. protected function checkBefore($before)
  675. {
  676. $hook = Container::get('hook');
  677. foreach ((array) $before as $behavior) {
  678. $result = $hook->exec($behavior);
  679. if (false === $result) {
  680. return false;
  681. }
  682. }
  683. }
  684. /**
  685. * 发起路由调度
  686. * @access protected
  687. * @param Request $request Request对象
  688. * @param mixed $route 路由地址
  689. * @param array $option 路由参数
  690. * @return Dispatch
  691. */
  692. protected function dispatch($request, $route, $option)
  693. {
  694. if ($route instanceof \Closure) {
  695. // 执行闭包
  696. $result = new CallbackDispatch($request, $this, $route);
  697. } elseif ($route instanceof Response) {
  698. $result = new ResponseDispatch($request, $this, $route);
  699. } elseif (isset($option['view']) && false !== $option['view']) {
  700. $result = new ViewDispatch($request, $this, $route, is_array($option['view']) ? $option['view'] : []);
  701. } elseif (!empty($option['redirect']) || 0 === strpos($route, '/') || strpos($route, '://')) {
  702. // 路由到重定向地址
  703. $result = new RedirectDispatch($request, $this, $route, [], isset($option['status']) ? $option['status'] : 301);
  704. } elseif (false !== strpos($route, '\\')) {
  705. // 路由到方法
  706. $result = $this->dispatchMethod($request, $route);
  707. } elseif (0 === strpos($route, '@')) {
  708. // 路由到控制器
  709. $result = $this->dispatchController($request, substr($route, 1));
  710. } else {
  711. // 路由到模块/控制器/操作
  712. $result = $this->dispatchModule($request, $route);
  713. }
  714. return $result;
  715. }
  716. /**
  717. * 解析URL地址为 模块/控制器/操作
  718. * @access protected
  719. * @param Request $request Request对象
  720. * @param string $route 路由地址
  721. * @return CallbackDispatch
  722. */
  723. protected function dispatchMethod($request, $route)
  724. {
  725. list($path, $var) = $this->parseUrlPath($route);
  726. $route = str_replace('/', '@', implode('/', $path));
  727. $method = strpos($route, '@') ? explode('@', $route) : $route;
  728. return new CallbackDispatch($request, $this, $method, $var);
  729. }
  730. /**
  731. * 解析URL地址为 模块/控制器/操作
  732. * @access protected
  733. * @param Request $request Request对象
  734. * @param string $route 路由地址
  735. * @return ControllerDispatch
  736. */
  737. protected function dispatchController($request, $route)
  738. {
  739. list($route, $var) = $this->parseUrlPath($route);
  740. $result = new ControllerDispatch($request, $this, implode('/', $route), $var);
  741. $request->setAction(array_pop($route));
  742. $request->setController($route ? array_pop($route) : $this->getConfig('default_controller'));
  743. $request->setModule($route ? array_pop($route) : $this->getConfig('default_module'));
  744. return $result;
  745. }
  746. /**
  747. * 解析URL地址为 模块/控制器/操作
  748. * @access protected
  749. * @param Request $request Request对象
  750. * @param string $route 路由地址
  751. * @return ModuleDispatch
  752. */
  753. protected function dispatchModule($request, $route)
  754. {
  755. list($path, $var) = $this->parseUrlPath($route);
  756. $action = array_pop($path);
  757. $controller = !empty($path) ? array_pop($path) : null;
  758. $module = $this->getConfig('app_multi_module') && !empty($path) ? array_pop($path) : null;
  759. $method = $request->method();
  760. if ($this->getConfig('use_action_prefix') && $this->router->getMethodPrefix($method)) {
  761. $prefix = $this->router->getMethodPrefix($method);
  762. // 操作方法前缀支持
  763. $action = 0 !== strpos($action, $prefix) ? $prefix . $action : $action;
  764. }
  765. // 设置当前请求的路由变量
  766. $request->setRouteVars($var);
  767. // 路由到模块/控制器/操作
  768. return new ModuleDispatch($request, $this, [$module, $controller, $action], ['convert' => false]);
  769. }
  770. /**
  771. * 路由检查
  772. * @access protected
  773. * @param array $option 路由参数
  774. * @param Request $request Request对象
  775. * @return bool
  776. */
  777. protected function checkOption($option, Request $request)
  778. {
  779. // 请求类型检测
  780. if (!empty($option['method'])) {
  781. if (is_string($option['method']) && false === stripos($option['method'], $request->method())) {
  782. return false;
  783. }
  784. }
  785. // AJAX PJAX 请求检查
  786. foreach (['ajax', 'pjax', 'mobile'] as $item) {
  787. if (isset($option[$item])) {
  788. $call = 'is' . $item;
  789. if ($option[$item] && !$request->$call() || !$option[$item] && $request->$call()) {
  790. return false;
  791. }
  792. }
  793. }
  794. // 伪静态后缀检测
  795. if ($request->url() != '/' && ((isset($option['ext']) && false === stripos('|' . $option['ext'] . '|', '|' . $request->ext() . '|'))
  796. || (isset($option['deny_ext']) && false !== stripos('|' . $option['deny_ext'] . '|', '|' . $request->ext() . '|')))) {
  797. return false;
  798. }
  799. // 域名检查
  800. if ((isset($option['domain']) && !in_array($option['domain'], [$request->host(true), $request->subDomain()]))) {
  801. return false;
  802. }
  803. // HTTPS检查
  804. if ((isset($option['https']) && $option['https'] && !$request->isSsl())
  805. || (isset($option['https']) && !$option['https'] && $request->isSsl())) {
  806. return false;
  807. }
  808. // 请求参数检查
  809. if (isset($option['filter'])) {
  810. foreach ($option['filter'] as $name => $value) {
  811. if ($request->param($name, '', null) != $value) {
  812. return false;
  813. }
  814. }
  815. }
  816. return true;
  817. }
  818. /**
  819. * 解析URL地址中的参数Request对象
  820. * @access protected
  821. * @param Request $request
  822. * @param string $rule 路由规则
  823. * @param array $var 变量
  824. * @return void
  825. */
  826. protected function parseUrlParams($request, $url, &$var = [])
  827. {
  828. if ($url) {
  829. if ($this->getConfig('url_param_type')) {
  830. $var += explode('|', $url);
  831. } else {
  832. preg_replace_callback('/(\w+)\|([^\|]+)/', function ($match) use (&$var) {
  833. $var[$match[1]] = strip_tags($match[2]);
  834. }, $url);
  835. }
  836. }
  837. }
  838. /**
  839. * 解析URL的pathinfo参数和变量
  840. * @access public
  841. * @param string $url URL地址
  842. * @return array
  843. */
  844. public function parseUrlPath($url)
  845. {
  846. // 分隔符替换 确保路由定义使用统一的分隔符
  847. $url = str_replace('|', '/', $url);
  848. $url = trim($url, '/');
  849. $var = [];
  850. if (false !== strpos($url, '?')) {
  851. // [模块/控制器/操作?]参数1=值1&参数2=值2...
  852. $info = parse_url($url);
  853. $path = explode('/', $info['path']);
  854. parse_str($info['query'], $var);
  855. } elseif (strpos($url, '/')) {
  856. // [模块/控制器/操作]
  857. $path = explode('/', $url);
  858. } elseif (false !== strpos($url, '=')) {
  859. // 参数1=值1&参数2=值2...
  860. $path = [];
  861. parse_str($url, $var);
  862. } else {
  863. $path = [$url];
  864. }
  865. return [$path, $var];
  866. }
  867. /**
  868. * 生成路由的正则规则
  869. * @access protected
  870. * @param string $rule 路由规则
  871. * @param array $match 匹配的变量
  872. * @param array $pattern 路由变量规则
  873. * @param array $option 路由参数
  874. * @param bool $completeMatch 路由是否完全匹配
  875. * @param string $suffix 路由正则变量后缀
  876. * @return string
  877. */
  878. protected function buildRuleRegex($rule, $match, $pattern = [], $option = [], $completeMatch = false, $suffix = '')
  879. {
  880. foreach ($match as $name) {
  881. $replace[] = $this->buildNameRegex($name, $pattern, $suffix);
  882. }
  883. // 是否区分 / 地址访问
  884. if ('/' != $rule) {
  885. if (!empty($option['remove_slash'])) {
  886. $rule = rtrim($rule, '/');
  887. } elseif (substr($rule, -1) == '/') {
  888. $rule = rtrim($rule, '/');
  889. $hasSlash = true;
  890. }
  891. }
  892. $regex = str_replace(array_unique($match), array_unique($replace), $rule);
  893. $regex = str_replace([')?/', ')/', ')?-', ')-', '\\\\/'], [')\/', ')\/', ')\-', ')\-', '\/'], $regex);
  894. if (isset($hasSlash)) {
  895. $regex .= '\/';
  896. }
  897. return $regex . ($completeMatch ? '$' : '');
  898. }
  899. /**
  900. * 生成路由变量的正则规则
  901. * @access protected
  902. * @param string $name 路由变量
  903. * @param string $pattern 变量规则
  904. * @param string $suffix 路由正则变量后缀
  905. * @return string
  906. */
  907. protected function buildNameRegex($name, $pattern, $suffix)
  908. {
  909. $optional = '';
  910. $slash = substr($name, 0, 1);
  911. if (in_array($slash, ['/', '-'])) {
  912. $prefix = '\\' . $slash;
  913. $name = substr($name, 1);
  914. $slash = substr($name, 0, 1);
  915. } else {
  916. $prefix = '';
  917. }
  918. if ('<' != $slash) {
  919. return $prefix . preg_quote($name, '/');
  920. }
  921. if (strpos($name, '?')) {
  922. $name = substr($name, 1, -2);
  923. $optional = '?';
  924. } elseif (strpos($name, '>')) {
  925. $name = substr($name, 1, -1);
  926. }
  927. if (isset($pattern[$name])) {
  928. $nameRule = $pattern[$name];
  929. if (0 === strpos($nameRule, '/') && '/' == substr($nameRule, -1)) {
  930. $nameRule = substr($nameRule, 1, -1);
  931. }
  932. } else {
  933. $nameRule = $this->getConfig('default_route_pattern');
  934. }
  935. return '(' . $prefix . '(?<' . $name . $suffix . '>' . $nameRule . '))' . $optional;
  936. }
  937. /**
  938. * 分析路由规则中的变量
  939. * @access protected
  940. * @param string $rule 路由规则
  941. * @return array
  942. */
  943. protected function parseVar($rule)
  944. {
  945. // 提取路由规则中的变量
  946. $var = [];
  947. if (preg_match_all('/<\w+\??>/', $rule, $matches)) {
  948. foreach ($matches[0] as $name) {
  949. $optional = false;
  950. if (strpos($name, '?')) {
  951. $name = substr($name, 1, -2);
  952. $optional = true;
  953. } else {
  954. $name = substr($name, 1, -1);
  955. }
  956. $var[$name] = $optional ? 2 : 1;
  957. }
  958. }
  959. return $var;
  960. }
  961. /**
  962. * 设置路由参数
  963. * @access public
  964. * @param string $method 方法名
  965. * @param array $args 调用参数
  966. * @return $this
  967. */
  968. public function __call($method, $args)
  969. {
  970. if (count($args) > 1) {
  971. $args[0] = $args;
  972. }
  973. array_unshift($args, $method);
  974. return call_user_func_array([$this, 'option'], $args);
  975. }
  976. public function __sleep()
  977. {
  978. return ['name', 'rule', 'route', 'method', 'vars', 'option', 'pattern', 'doAfter'];
  979. }
  980. public function __wakeup()
  981. {
  982. $this->router = Container::get('route');
  983. }
  984. public function __debugInfo()
  985. {
  986. $data = get_object_vars($this);
  987. unset($data['parent'], $data['router'], $data['route']);
  988. return $data;
  989. }
  990. }