Completed
Push — 6.0 ( 7d6f90...b04f47 )
by yun
02:12
created

Rule::dispatch()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 4.1755

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 4
eloc 9
c 2
b 0
f 0
nc 4
nop 3
dl 0
loc 16
ccs 7
cts 9
cp 0.7778
crap 4.1755
rs 9.9666
1
<?php
2
// +----------------------------------------------------------------------
3
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
4
// +----------------------------------------------------------------------
5
// | Copyright (c) 2006~2019 http://thinkphp.cn All rights reserved.
6
// +----------------------------------------------------------------------
7
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
8
// +----------------------------------------------------------------------
9
// | Author: liu21st <[email protected]>
10
// +----------------------------------------------------------------------
11
declare (strict_types = 1);
12
13
namespace think\route;
14
15
use Closure;
16
use think\Container;
17
use think\middleware\AllowCrossDomain;
18
use think\middleware\CheckRequestCache;
19
use think\middleware\FormTokenCheck;
20
use think\Request;
21
use think\Response;
22
use think\Route;
23
use think\route\dispatch\Callback as CallbackDispatch;
24
use think\route\dispatch\Controller as ControllerDispatch;
25
use think\route\dispatch\Redirect as RedirectDispatch;
0 ignored issues
show
Bug introduced by
The type think\route\dispatch\Redirect was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
26
use think\route\dispatch\Response as ResponseDispatch;
0 ignored issues
show
Bug introduced by
The type think\route\dispatch\Response was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
27
use think\route\dispatch\View as ViewDispatch;
0 ignored issues
show
Bug introduced by
The type think\route\dispatch\View was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

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