Passed
Push — 6.0 ( e69792...ffe383 )
by liu
12:23
created

Rule::call()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 0
cts 2
cp 0
crap 2
rs 10
c 1
b 0
f 0
1
<?php
2
// +----------------------------------------------------------------------
3
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
4
// +----------------------------------------------------------------------
5
// | Copyright (c) 2006~2021 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\Route;
22
use think\route\dispatch\Callback as CallbackDispatch;
23
use think\route\dispatch\Controller as ControllerDispatch;
24
25
/**
26
 * 路由规则基础类
27
 */
28
abstract class Rule
29
{
30
    /**
31
     * 路由标识
32
     * @var string
33
     */
34
    protected $name;
35
36
    /**
37
     * 所在域名
38
     * @var string
39
     */
40
    protected $domain;
41
42
    /**
43
     * 路由对象
44
     * @var Route
45
     */
46
    protected $router;
47
48
    /**
49
     * 路由所属分组
50
     * @var RuleGroup
51
     */
52
    protected $parent;
53
54
    /**
55
     * 路由规则
56
     * @var mixed
57
     */
58
    protected $rule;
59
60
    /**
61
     * 路由地址
62
     * @var string|Closure
63
     */
64
    protected $route;
65
66
    /**
67
     * 请求类型
68
     * @var string
69
     */
70
    protected $method;
71
72
    /**
73
     * 路由变量
74
     * @var array
75
     */
76
    protected $vars = [];
77
78
    /**
79
     * 路由参数
80
     * @var array
81
     */
82
    protected $option = [];
83
84
    /**
85
     * 路由变量规则
86
     * @var array
87
     */
88
    protected $pattern = [];
89
90
    /**
91
     * 需要和分组合并的路由参数
92
     * @var array
93
     */
94
    protected $mergeOptions = ['model', 'append', 'middleware'];
95
96
    abstract public function check(Request $request, string $url, bool $completeMatch = false);
97
98
    /**
99
     * 设置路由参数
100
     * @access public
101
     * @param  array $option 参数
102
     * @return $this
103
     */
104
    public function option(array $option)
105
    {
106
        $this->option = array_merge($this->option, $option);
107
108
        return $this;
109
    }
110
111
    /**
112
     * 设置单个路由参数
113
     * @access public
114
     * @param  string $name  参数名
115
     * @param  mixed  $value 值
116
     * @return $this
117
     */
118 33
    public function setOption(string $name, $value)
119
    {
120 33
        $this->option[$name] = $value;
121
122 33
        return $this;
123
    }
124
125
    /**
126
     * 注册变量规则
127
     * @access public
128
     * @param  array $pattern 变量规则
129
     * @return $this
130
     */
131
    public function pattern(array $pattern)
132
    {
133
        $this->pattern = array_merge($this->pattern, $pattern);
134
135
        return $this;
136
    }
137
138
    /**
139
     * 设置标识
140
     * @access public
141
     * @param  string $name 标识名
142
     * @return $this
143
     */
144
    public function name(string $name)
145
    {
146
        $this->name = $name;
147
148
        return $this;
149
    }
150
151
    /**
152
     * 获取路由对象
153
     * @access public
154
     * @return Route
155
     */
156 6
    public function getRouter(): Route
157
    {
158 6
        return $this->router;
159
    }
160
161
    /**
162
     * 获取Name
163
     * @access public
164
     * @return string
165
     */
166
    public function getName(): string
167
    {
168
        return $this->name ?: '';
169
    }
170
171
    /**
172
     * 获取当前路由规则
173
     * @access public
174
     * @return mixed
175
     */
176 12
    public function getRule()
177
    {
178 12
        return $this->rule;
179
    }
180
181
    /**
182
     * 获取当前路由地址
183
     * @access public
184
     * @return mixed
185
     */
186 30
    public function getRoute()
187
    {
188 30
        return $this->route;
189
    }
190
191
    /**
192
     * 获取当前路由的变量
193
     * @access public
194
     * @return array
195
     */
196 3
    public function getVars(): array
197
    {
198 3
        return $this->vars;
199
    }
200
201
    /**
202
     * 获取Parent对象
203
     * @access public
204
     * @return $this|null
205
     */
206
    public function getParent()
207
    {
208
        return $this->parent;
209
    }
210
211
    /**
212
     * 获取路由所在域名
213
     * @access public
214
     * @return string
215
     */
216 12
    public function getDomain(): string
217
    {
218 12
        return $this->domain ?: $this->parent->getDomain();
219
    }
220
221
    /**
222
     * 获取路由参数
223
     * @access public
224
     * @param  string $name 变量名
225
     * @return mixed
226
     */
227 12
    public function config(string $name = '')
228
    {
229 12
        return $this->router->config($name);
230
    }
231
232
    /**
233
     * 获取变量规则定义
234
     * @access public
235
     * @param  string $name 变量名
236
     * @return mixed
237
     */
238 30
    public function getPattern(string $name = '')
239
    {
240 30
        $pattern = $this->pattern;
241
242 30
        if ($this->parent) {
243 30
            $pattern = array_merge($this->parent->getPattern(), $pattern);
244
        }
245
246 30
        if ('' === $name) {
247 30
            return $pattern;
248
        }
249
250
        return $pattern[$name] ?? null;
251
    }
252
253
    /**
254
     * 获取路由参数定义
255
     * @access public
256
     * @param  string $name 参数名
257
     * @param  mixed  $default 默认值
258
     * @return mixed
259
     */
260 33
    public function getOption(string $name = '', $default = null)
261
    {
262 33
        $option = $this->option;
263
264 33
        if ($this->parent) {
265 30
            $parentOption = $this->parent->getOption();
266
267
            // 合并分组参数
268 30
            foreach ($this->mergeOptions as $item) {
269 30
                if (isset($parentOption[$item]) && isset($option[$item])) {
270 10
                    $option[$item] = array_merge($parentOption[$item], $option[$item]);
271
                }
272
            }
273
274 30
            $option = array_merge($parentOption, $option);
275
        }
276
277 33
        if ('' === $name) {
278 33
            return $option;
279
        }
280
281 12
        return $option[$name] ?? $default;
282
    }
283
284
    /**
285
     * 获取当前路由的请求类型
286
     * @access public
287
     * @return string
288
     */
289 12
    public function getMethod(): string
290
    {
291 12
        return strtolower($this->method);
292
    }
293
294
    /**
295
     * 设置路由请求类型
296
     * @access public
297
     * @param  string $method 请求类型
298
     * @return $this
299
     */
300
    public function method(string $method)
301
    {
302
        return $this->setOption('method', strtolower($method));
303
    }
304
305
    /**
306
     * 检查后缀
307
     * @access public
308
     * @param  string $ext URL后缀
309
     * @return $this
310
     */
311
    public function ext(string $ext = '')
312
    {
313
        return $this->setOption('ext', $ext);
314
    }
315
316
    /**
317
     * 检查禁止后缀
318
     * @access public
319
     * @param  string $ext URL后缀
320
     * @return $this
321
     */
322
    public function denyExt(string $ext = '')
323
    {
324
        return $this->setOption('deny_ext', $ext);
325
    }
326
327
    /**
328
     * 检查域名
329
     * @access public
330
     * @param  string $domain 域名
331
     * @return $this
332
     */
333
    public function domain(string $domain)
334
    {
335
        $this->domain = $domain;
336
        return $this->setOption('domain', $domain);
337
    }
338
339
    /**
340
     * 设置参数过滤检查
341
     * @access public
342
     * @param  array $filter 参数过滤
343
     * @return $this
344
     */
345
    public function filter(array $filter)
346
    {
347
        $this->option['filter'] = $filter;
348
349
        return $this;
350
    }
351
352
    /**
353
     * 绑定模型
354
     * @access public
355
     * @param  array|string|Closure $var  路由变量名 多个使用 & 分割
356
     * @param  string|Closure       $model 绑定模型类
357
     * @param  bool                  $exception 是否抛出异常
358
     * @return $this
359
     */
360
    public function model($var, $model = null, bool $exception = true)
361
    {
362
        if ($var instanceof Closure) {
363
            $this->option['model'][] = $var;
364
        } elseif (is_array($var)) {
365
            $this->option['model'] = $var;
366
        } elseif (is_null($model)) {
367
            $this->option['model']['id'] = [$var, true];
368
        } else {
369
            $this->option['model'][$var] = [$model, $exception];
370
        }
371
372
        return $this;
373
    }
374
375
    /**
376
     * 附加路由隐式参数
377
     * @access public
378
     * @param  array $append 追加参数
379
     * @return $this
380
     */
381
    public function append(array $append = [])
382
    {
383
        $this->option['append'] = $append;
384
385
        return $this;
386
    }
387
388
    /**
389
     * 绑定验证
390
     * @access public
391
     * @param  mixed  $validate 验证器类
392
     * @param  string $scene 验证场景
393
     * @param  array  $message 验证提示
394
     * @param  bool   $batch 批量验证
395
     * @return $this
396
     */
397
    public function validate($validate, string $scene = null, array $message = [], bool $batch = false)
398
    {
399
        $this->option['validate'] = [$validate, $scene, $message, $batch];
400
401
        return $this;
402
    }
403
404
    /**
405
     * 指定路由中间件
406
     * @access public
407
     * @param string|array|Closure $middleware 中间件
408
     * @param mixed $params 参数
409
     * @return $this
410
     */
411 3
    public function middleware($middleware, ...$params)
412
    {
413 3
        if (empty($params) && is_array($middleware)) {
414
            $this->option['middleware'] = $middleware;
415
        } else {
416 3
            foreach ((array) $middleware as $item) {
417 3
                $this->option['middleware'][] = [$item, $params];
418
            }
419
        }
420
421 3
        return $this;
422
    }
423
424
    /**
425
     * 允许跨域
426
     * @access public
427
     * @param  array $header 自定义Header
428
     * @return $this
429
     */
430 3
    public function allowCrossDomain(array $header = [])
431
    {
432 3
        return $this->middleware(AllowCrossDomain::class, $header);
433
    }
434
435
    /**
436
     * 表单令牌验证
437
     * @access public
438
     * @param  string $token 表单令牌token名称
439
     * @return $this
440
     */
441
    public function token(string $token = '__token__')
442
    {
443
        return $this->middleware(FormTokenCheck::class, $token);
444
    }
445
446
    /**
447
     * 设置路由缓存
448
     * @access public
449
     * @param  array|string $cache 缓存
450
     * @return $this
451
     */
452
    public function cache($cache)
453
    {
454
        return $this->middleware(CheckRequestCache::class, $cache);
455
    }
456
457
    /**
458
     * 检查URL分隔符
459
     * @access public
460
     * @param  string $depr URL分隔符
461
     * @return $this
462
     */
463
    public function depr(string $depr)
464
    {
465
        return $this->setOption('param_depr', $depr);
466
    }
467
468
    /**
469
     * 设置需要合并的路由参数
470
     * @access public
471
     * @param  array $option 路由参数
472
     * @return $this
473
     */
474
    public function mergeOptions(array $option = [])
475
    {
476
        $this->mergeOptions = array_merge($this->mergeOptions, $option);
477
        return $this;
478
    }
479
480
    /**
481
     * 检查是否为HTTPS请求
482
     * @access public
483
     * @param  bool $https 是否为HTTPS
484
     * @return $this
485
     */
486
    public function https(bool $https = true)
487
    {
488
        return $this->setOption('https', $https);
489
    }
490
491
    /**
492
     * 检查是否为JSON请求
493
     * @access public
494
     * @param  bool $json 是否为JSON
495
     * @return $this
496
     */
497
    public function json(bool $json = true)
498
    {
499
        return $this->setOption('json', $json);
500
    }
501
502
    /**
503
     * 检查是否为AJAX请求
504
     * @access public
505
     * @param  bool $ajax 是否为AJAX
506
     * @return $this
507
     */
508
    public function ajax(bool $ajax = true)
509
    {
510
        return $this->setOption('ajax', $ajax);
511
    }
512
513
    /**
514
     * 检查是否为PJAX请求
515
     * @access public
516
     * @param  bool $pjax 是否为PJAX
517
     * @return $this
518
     */
519
    public function pjax(bool $pjax = true)
520
    {
521
        return $this->setOption('pjax', $pjax);
522
    }
523
524
    /**
525
     * 路由到一个模板地址 需要额外传入的模板变量
526
     * @access public
527
     * @param  array $view 视图
528
     * @return $this
529
     */
530
    public function view(array $view = [])
531
    {
532
        return $this->setOption('view', $view);
533
    }
534
535
    /**
536
     * 闭包检测
537
     * @access public
538
     * @param  callable $call 闭包
539
     * @return $this
540
     */
541
    public function call(callable $call)
542
    {
543
        return $this->setOption('call', $call);
544
    }
545
546
    /**
547
     * 设置路由完整匹配
548
     * @access public
549
     * @param  bool $match 是否完整匹配
550
     * @return $this
551
     */
552 33
    public function completeMatch(bool $match = true)
553
    {
554 33
        return $this->setOption('complete_match', $match);
555
    }
556
557
    /**
558
     * 是否去除URL最后的斜线
559
     * @access public
560
     * @param  bool $remove 是否去除最后斜线
561
     * @return $this
562
     */
563
    public function removeSlash(bool $remove = true)
564
    {
565
        return $this->setOption('remove_slash', $remove);
566
    }
567
568
    /**
569
     * 设置路由规则全局有效
570
     * @access public
571
     * @return $this
572
     */
573
    public function crossDomainRule()
574
    {
575
        if ($this instanceof RuleGroup) {
576
            $method = '*';
577
        } else {
578
            $method = $this->method;
579
        }
580
581
        $this->router->setCrossDomainRule($this, $method);
582
583
        return $this;
584
    }
585
586 30
    /**
587
     * 解析匹配到的规则路由
588 30
     * @access public
589
     * @param  Request $request 请求对象
590
     * @param  string  $rule 路由规则
591
     * @param  mixed   $route 路由地址
592
     * @param  string  $url URL地址
593
     * @param  array   $option 路由参数
594 30
     * @param  array   $matches 匹配的变量
595 30
     * @return Dispatch
596 30
     */
597 30
    public function parseRule(Request $request, string $rule, $route, string $url, array $option = [], array $matches = []): Dispatch
598 6
    {
599 6
        if (is_string($route) && isset($option['prefix'])) {
600
            // 路由地址前缀
601 6
            $route = $option['prefix'] . $route;
602 6
        }
603
604 6
        // 替换路由地址中的变量
605 2
        $extraParams = true;
606
        $search      = $replace      = [];
607
        $depr        = $this->router->config('pathinfo_depr');
608
        foreach ($matches as $key => $value) {
609 30
            $search[]  = '<' . $key . '>';
610 12
            $replace[] = $value;
611
612
            $search[]  = ':' . $key;
613
            $replace[] = $value;
614 30
615 30
            if (strpos($value, $depr)) {
0 ignored issues
show
Bug introduced by
It seems like $depr can also be of type null; however, parameter $needle of strpos() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

615
            if (strpos($value, /** @scrutinizer ignore-type */ $depr)) {
Loading history...
616 30
                $extraParams = false;
617 30
            }
618
        }
619
620 30
        if (is_string($route)) {
621
            $route = str_replace($search, $replace, $route);
622
        }
623 30
624
        // 解析额外参数
625
        if ($extraParams) {
626
            $count = substr_count($rule, '/');
627
            $url   = array_slice(explode('|', $url), $count + 1);
628
            $this->parseUrlParams(implode('|', $url), $matches);
629
        }
630
631
        $this->vars = $matches;
632
633
        // 发起路由调度
634 30
        return $this->dispatch($request, $route, $option);
635
    }
636 30
637
    /**
638 30
     * 发起路由调度
639
     * @access protected
640 21
     * @param  Request $request Request对象
641 12
     * @param  mixed   $route  路由地址
642
     * @param  array   $option 路由参数
643
     * @return Dispatch
644
     */
645
    protected function dispatch(Request $request, $route, array $option): Dispatch
646
    {
647 12
        if (is_subclass_of($route, Dispatch::class)) {
648
            $result = new $route($request, $this, $route, $this->vars);
649
        } elseif ($route instanceof Closure) {
650 30
            // 执行闭包
651
            $result = new CallbackDispatch($request, $this, $route, $this->vars);
652
        } elseif (false !== strpos($route, '@') || false !== strpos($route, '::') || false !== strpos($route, '\\')) {
653
            // 路由到类的方法
654
            $route  = str_replace('::', '@', $route);
655
            $result = $this->dispatchMethod($request, $route);
656
        } else {
657
            // 路由到控制器/操作
658
            $result = $this->dispatchController($request, $route);
659
        }
660
661
        return $result;
662
    }
663
664
    /**
665
     * 解析URL地址为 模块/控制器/操作
666
     * @access protected
667
     * @param  Request $request Request对象
668
     * @param  string  $route 路由地址
669
     * @return CallbackDispatch
670
     */
671
    protected function dispatchMethod(Request $request, string $route): CallbackDispatch
672
    {
673
        $path = $this->parseUrlPath($route);
674
675
        $route  = str_replace('/', '@', implode('/', $path));
676
        $method = strpos($route, '@') ? explode('@', $route) : $route;
677 12
678
        return new CallbackDispatch($request, $this, $method, $this->vars);
679 12
    }
680
681 12
    /**
682 12
     * 解析URL地址为 模块/控制器/操作
683
     * @access protected
684
     * @param  Request $request Request对象
685 12
     * @param  string  $route 路由地址
686
     * @return ControllerDispatch
687
     */
688
    protected function dispatchController(Request $request, string $route): ControllerDispatch
689
    {
690
        $path = $this->parseUrlPath($route);
691
692
        $action     = array_pop($path);
693
        $controller = !empty($path) ? array_pop($path) : null;
694
695 33
        // 路由到模块/控制器/操作
696
        return new ControllerDispatch($request, $this, [$controller, $action], $this->vars);
697
    }
698 33
699
    /**
700
     * 路由检查
701
     * @access protected
702
     * @param  array   $option 路由参数
703
     * @param  Request $request Request对象
704
     * @return bool
705 33
     */
706 33
    protected function checkOption(array $option, Request $request): bool
707
    {
708
        // 请求类型检测
709 11
        if (!empty($option['method'])) {
710
            if (is_string($option['method']) && false === stripos($option['method'], $request->method())) {
711
                return false;
712
            }
713
        }
714
715 33
        // AJAX PJAX 请求检查
716 33
        foreach (['ajax', 'pjax', 'json'] as $item) {
717
            if (isset($option[$item])) {
718
                $call = 'is' . $item;
719
                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...
720
                    return false;
721 33
                }
722
            }
723
        }
724
725
        // 伪静态后缀检测
726 33
        if ($request->url() != '/' && ((isset($option['ext']) && false === stripos('|' . $option['ext'] . '|', '|' . $request->ext() . '|'))
727 33
            || (isset($option['deny_ext']) && false !== stripos('|' . $option['deny_ext'] . '|', '|' . $request->ext() . '|')))) {
728
            return false;
729
        }
730
731
        // 域名检查
732 33
        if ((isset($option['domain']) && !in_array($option['domain'], [$request->host(true), $request->subDomain()]))) {
733
            return false;
734
        }
735
736
        // HTTPS检查
737
        if ((isset($option['https']) && $option['https'] && !$request->isSsl())
738
            || (isset($option['https']) && !$option['https'] && $request->isSsl())) {
739
            return false;
740 33
        }
741
742
        // 请求参数检查
743
        if (isset($option['filter'])) {
744
            foreach ($option['filter'] as $name => $value) {
745
                if ($request->param($name, '', null) != $value) {
746
                    return false;
747
                }
748
            }
749
        }
750 30
751
        // 闭包检查
752 30
        if (isset($option['call']) && is_callable($option['call'])) {
753
            if (false === $option['call']($this, $request)) {
754
                return false;
755
            }
756
        }
757 30
758
        return true;
759
    }
760
761
    /**
762
     * 解析URL地址中的参数Request对象
763
     * @access protected
764
     * @param  string $rule 路由规则
765 15
     * @param  array  $var 变量
766
     * @return void
767
     */
768 15
    protected function parseUrlParams(string $url, array &$var = []): void
769 15
    {
770
        if ($url) {
771 15
            preg_replace_callback('/(\w+)\|([^\|]+)/', function ($match) use (&$var) {
772
                $var[$match[1]] = strip_tags($match[2]);
773 12
            }, $url);
774
        }
775 3
    }
776
777
    /**
778 15
     * 解析URL的pathinfo参数
779
     * @access public
780
     * @param  string $url URL地址
781
     * @return array
782
     */
783
    public function parseUrlPath(string $url): array
784
    {
785
        // 分隔符替换 确保路由定义使用统一的分隔符
786
        $url = str_replace('|', '/', $url);
787
        $url = trim($url, '/');
788
789
        if (strpos($url, '/')) {
790
            // [控制器/操作]
791
            $path = explode('/', $url);
792 6
        } else {
793
            $path = [$url];
794 6
        }
795 6
796 6
        return $path;
797 6
    }
798 6
799
    /**
800
     * 生成路由的正则规则
801
     * @access protected
802
     * @param  string $rule 路由规则
803 6
     * @param  array  $match 匹配的变量
804 6
     * @param  array  $pattern   路由变量规则
805
     * @param  array  $option    路由参数
806 6
     * @param  bool   $completeMatch   路由是否完全匹配
807
     * @param  string $suffix   路由正则变量后缀
808
     * @return string
809
     */
810
    protected function buildRuleRegex(string $rule, array $match, array $pattern = [], array $option = [], bool $completeMatch = false, string $suffix = ''): string
811
    {
812 6
        foreach ($match as $name) {
813 6
            $value = $this->buildNameRegex($name, $pattern, $suffix);
814
            if ($value) {
815 6
                $origin[]  = $name;
816
                $replace[] = $value;
817
            }
818
        }
819 6
820
        // 是否区分 / 地址访问
821
        if ('/' != $rule) {
822
            if (!empty($option['remove_slash'])) {
823
                $rule = rtrim($rule, '/');
824
            } elseif (substr($rule, -1) == '/') {
825
                $rule     = rtrim($rule, '/');
826
                $hasSlash = true;
827
            }
828
        }
829
830 6
        $regex = isset($replace) ? str_replace($origin, $replace, $rule) : $rule;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $origin does not seem to be defined for all execution paths leading up to this point.
Loading history...
831
        $regex = str_replace([')?/', ')?-'], [')/', ')-'], $regex);
832 6
833 6
        if (isset($hasSlash)) {
834
            $regex .= '/';
835 6
        }
836 6
837 6
        return $regex . ($completeMatch ? '$' : '');
838 6
    }
839
840
    /**
841
     * 生成路由变量的正则规则
842
     * @access protected
843 6
     * @param  string $name    路由变量
844 6
     * @param  array  $pattern 变量规则
845
     * @param  string $suffix  路由正则变量后缀
846
     * @return string
847 6
     */
848
    protected function buildNameRegex(string $name, array $pattern, string $suffix): string
849
    {
850 6
        $optional = '';
851 6
        $slash    = substr($name, 0, 1);
852
853
        if (in_array($slash, ['/', '-'])) {
854 6
            $prefix = $slash;
855
            $name   = substr($name, 1);
856
            $slash  = substr($name, 0, 1);
857
        } else {
858
            $prefix = '';
859
        }
860 6
861
        if ('<' != $slash) {
862
            return '';
863 6
        }
864
865
        if (strpos($name, '?')) {
866
            $name     = substr($name, 1, -2);
867
            $optional = '?';
868
        } elseif (strpos($name, '>')) {
869
            $name = substr($name, 1, -1);
870
        }
871
872
        if (isset($pattern[$name])) {
873
            $nameRule = $pattern[$name];
874
            if (0 === strpos($nameRule, '/') && '/' == substr($nameRule, -1)) {
875
                $nameRule = substr($nameRule, 1, -1);
876
            }
877
        } else {
878
            $nameRule = $this->router->config('default_route_pattern');
879
        }
880
881
        return '(' . $prefix . '(?<' . $name . $suffix . '>' . $nameRule . '))' . $optional;
882
    }
883
884
    /**
885
     * 设置路由参数
886
     * @access public
887
     * @param  string $method 方法名
888
     * @param  array  $args   调用参数
889
     * @return $this
890
     */
891
    public function __call($method, $args)
892
    {
893
        if (count($args) > 1) {
894
            $args[0] = $args;
895
        }
896
        array_unshift($args, $method);
897
898
        return call_user_func_array([$this, 'setOption'], $args);
899
    }
900
901
    public function __sleep()
902
    {
903
        return ['name', 'rule', 'route', 'method', 'vars', 'option', 'pattern'];
904
    }
905
906
    public function __wakeup()
907
    {
908
        $this->router = Container::pull('route');
909
    }
910
911
    public function __debugInfo()
912
    {
913
        return [
914
            'name'    => $this->name,
915
            'rule'    => $this->rule,
916
            'route'   => $this->route,
917
            'method'  => $this->method,
918
            'vars'    => $this->vars,
919
            'option'  => $this->option,
920
            'pattern' => $this->pattern,
921
        ];
922
    }
923
}
924