Completed
Push — 6.0 ( e89165...09da7f )
by liu
06:38 queued 15s
created

Rule::view()   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 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 0
b 0
f 0
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;
26
use think\route\dispatch\Response as ResponseDispatch;
27
use think\route\dispatch\View as ViewDispatch;
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);
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function check()
Loading history...
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
    public function setOption(string $name, $value)
123
    {
124
        $this->option[$name] = $value;
125
126
        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
    public function getRouter(): Route
161
    {
162
        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
    public function getRule()
181
    {
182
        return $this->rule;
183
    }
184
185
    /**
186
     * 获取当前路由地址
187
     * @access public
188
     * @return mixed
189
     */
190
    public function getRoute()
191
    {
192
        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
    public function config(string $name = '')
232
    {
233
        return $this->router->config($name);
234
    }
235
236
    /**
237
     * 获取变量规则定义
238
     * @access public
239
     * @param  string $name 变量名
240
     * @return mixed
241
     */
242
    public function getPattern(string $name = '')
243
    {
244
        if ('' === $name) {
245
            return $this->pattern;
246
        }
247
248
        return $this->pattern[$name] ?? null;
249
    }
250
251
    /**
252
     * 获取路由参数定义
253
     * @access public
254
     * @param  string $name 参数名
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
255
     * @param  mixed  $default 默认值
256
     * @return mixed
257
     */
258
    public function getOption(string $name = '', $default = null)
259
    {
260
        if ('' === $name) {
261
            return $this->option;
262
        }
263
264
        return $this->option[$name] ?? $default;
265
    }
266
267
    /**
268
     * 获取当前路由的请求类型
269
     * @access public
270
     * @return string
271
     */
272
    public function getMethod(): string
273
    {
274
        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  路由变量名 多个使用 & 分割
0 ignored issues
show
Coding Style introduced by
Expected 7 spaces after parameter name; 2 found
Loading history...
339
     * @param  string|Closure       $model 绑定模型类
0 ignored issues
show
Coding Style introduced by
Expected 5 spaces after parameter name; 1 found
Loading history...
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 验证场景
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
376
     * @param  array  $message 验证提示
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 1 found
Loading history...
377
     * @param  bool   $batch 批量验证
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
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                $param 参数
0 ignored issues
show
Coding Style introduced by
Expected 6 spaces after parameter name; 1 found
Loading history...
392
     * @return $this
393
     */
394
    public function middleware($middleware, $param = null)
395
    {
396
        if (is_null($param) && is_array($middleware)) {
397
            $this->option['middleware'] = $middleware;
398
        } else {
399
            foreach ((array) $middleware as $item) {
400
                $this->option['middleware'][] = [$item, $param];
401
            }
402
        }
403
404
        return $this;
405
    }
406
407
    /**
408
     * 允许跨域
409
     * @access public
410
     * @param  array $header 自定义Header
411
     * @return $this
412
     */
413
    public function allowCrossDomain(array $header = [])
414
    {
415
        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  bool|array $view 视图
511
     * @return $this
512
     */
513
    public function view($view = true)
514
    {
515
        return $this->setOption('view', $view);
516
    }
517
518
    /**
519
     * 当前路由为重定向
520
     * @access public
521
     * @param  bool $redirect 是否为重定向
522
     * @return $this
523
     */
524
    public function redirect(bool $redirect = true)
525
    {
526
        return $this->setOption('redirect', $redirect);
527
    }
528
529
    /**
530
     * 设置status
531
     * @access public
532
     * @param  int $status 状态码
533
     * @return $this
534
     */
535
    public function status(int $status)
536
    {
537
        return $this->setOption('status', $status);
538
    }
539
540
    /**
541
     * 设置路由完整匹配
542
     * @access public
543
     * @param  bool $match 是否完整匹配
544
     * @return $this
545
     */
546
    public function completeMatch(bool $match = true)
547
    {
548
        return $this->setOption('complete_match', $match);
549
    }
550
551
    /**
552
     * 是否去除URL最后的斜线
553
     * @access public
554
     * @param  bool $remove 是否去除最后斜线
555
     * @return $this
556
     */
557
    public function removeSlash(bool $remove = true)
558
    {
559
        return $this->setOption('remove_slash', $remove);
560
    }
561
562
    /**
563
     * 设置路由规则全局有效
564
     * @access public
565
     * @return $this
566
     */
567
    public function crossDomainRule()
568
    {
569
        if ($this instanceof RuleGroup) {
570
            $method = '*';
571
        } else {
572
            $method = $this->method;
573
        }
574
575
        $this->router->setCrossDomainRule($this, $method);
576
577
        return $this;
578
    }
579
580
    /**
581
     * 合并分组参数
582
     * @access public
583
     * @return array
584
     */
585
    public function mergeGroupOptions(): array
586
    {
587
        $parentOption = $this->parent->getOption();
588
        // 合并分组参数
589
        foreach ($this->mergeOptions as $item) {
590
            if (isset($parentOption[$item]) && isset($this->option[$item])) {
591
                $this->option[$item] = array_merge($parentOption[$item], $this->option[$item]);
592
            }
593
        }
594
595
        $this->option = array_merge($parentOption, $this->option);
596
597
        return $this->option;
598
    }
599
600
    /**
601
     * 解析匹配到的规则路由
602
     * @access public
603
     * @param  Request $request 请求对象
604
     * @param  string  $rule 路由规则
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
605
     * @param  mixed   $route 路由地址
0 ignored issues
show
Coding Style introduced by
Expected 3 spaces after parameter name; 1 found
Loading history...
606
     * @param  string  $url URL地址
0 ignored issues
show
Coding Style introduced by
Expected 5 spaces after parameter name; 1 found
Loading history...
607
     * @param  array   $option 路由参数
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 1 found
Loading history...
608
     * @param  array   $matches 匹配的变量
609
     * @return Dispatch
610
     */
611
    public function parseRule(Request $request, string $rule, $route, string $url, array $option = [], array $matches = []): Dispatch
612
    {
613
        if (is_string($route) && isset($option['prefix'])) {
614
            // 路由地址前缀
615
            $route = $option['prefix'] . $route;
616
        }
617
618
        // 替换路由地址中的变量
619
        if (is_string($route) && !empty($matches)) {
620
            $search = $replace = [];
621
622
            foreach ($matches as $key => $value) {
623
                $search[]  = '<' . $key . '>';
624
                $replace[] = $value;
625
626
                $search[]  = ':' . $key;
627
                $replace[] = $value;
628
            }
629
630
            $route = str_replace($search, $replace, $route);
631
        }
632
633
        // 解析额外参数
634
        $count = substr_count($rule, '/');
635
        $url   = array_slice(explode('|', $url), $count + 1);
636
        $this->parseUrlParams(implode('|', $url), $matches);
637
638
        $this->vars = $matches;
639
640
        // 发起路由调度
641
        return $this->dispatch($request, $route, $option);
642
    }
643
644
    /**
645
     * 发起路由调度
646
     * @access protected
647
     * @param  Request $request Request对象
648
     * @param  mixed   $route  路由地址
0 ignored issues
show
Coding Style introduced by
Expected 3 spaces after parameter name; 2 found
Loading history...
649
     * @param  array   $option 路由参数
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 1 found
Loading history...
650
     * @return Dispatch
651
     */
652
    protected function dispatch(Request $request, $route, array $option): Dispatch
653
    {
654
        if ($route instanceof Dispatch) {
655
            $result = $route;
656
        } elseif ($route instanceof Closure) {
657
            // 执行闭包
658
            $result = new CallbackDispatch($request, $this, $route, $this->vars);
659
        } elseif ($route instanceof Response) {
660
            $result = new ResponseDispatch($request, $this, $route);
661
        } elseif (isset($option['view']) && false !== $option['view']) {
662
            $result = new ViewDispatch($request, $this, $route, is_array($option['view']) ? $option['view'] : $this->vars);
663
        } elseif (!empty($option['redirect'])) {
664
            // 路由到重定向地址
665
            $result = new RedirectDispatch($request, $this, $route, $this->vars, $option['status'] ?? 301);
666
        } elseif (false !== strpos($route, '\\')) {
667
            // 路由到类的方法
668
            $result = $this->dispatchMethod($request, $route);
669
        } else {
670
            // 路由到控制器/操作
671
            $result = $this->dispatchController($request, $route);
672
        }
673
674
        return $result;
675
    }
676
677
    /**
678
     * 解析URL地址为 模块/控制器/操作
679
     * @access protected
680
     * @param  Request $request Request对象
681
     * @param  string  $route 路由地址
0 ignored issues
show
Coding Style introduced by
Expected 3 spaces after parameter name; 1 found
Loading history...
682
     * @return CallbackDispatch
683
     */
684
    protected function dispatchMethod(Request $request, string $route): CallbackDispatch
685
    {
686
        $path = $this->parseUrlPath($route);
687
688
        $route  = str_replace('/', '@', implode('/', $path));
689
        $method = strpos($route, '@') ? explode('@', $route) : $route;
690
691
        return new CallbackDispatch($request, $this, $method, $this->vars);
692
    }
693
694
    /**
695
     * 解析URL地址为 模块/控制器/操作
696
     * @access protected
697
     * @param  Request $request Request对象
698
     * @param  string  $route 路由地址
0 ignored issues
show
Coding Style introduced by
Expected 3 spaces after parameter name; 1 found
Loading history...
699
     * @return ControllerDispatch
700
     */
701
    protected function dispatchController(Request $request, string $route): ControllerDispatch
702
    {
703
        $path = $this->parseUrlPath($route);
704
705
        $action     = array_pop($path);
706
        $controller = !empty($path) ? array_pop($path) : null;
707
708
        // 路由到模块/控制器/操作
709
        return new ControllerDispatch($request, $this, [$controller, $action], $this->vars);
710
    }
711
712
    /**
713
     * 路由检查
714
     * @access protected
715
     * @param  array   $option 路由参数
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 1 found
Loading history...
716
     * @param  Request $request Request对象
717
     * @return bool
718
     */
719
    protected function checkOption(array $option, Request $request): bool
720
    {
721
        // 请求类型检测
722
        if (!empty($option['method'])) {
723
            if (is_string($option['method']) && false === stripos($option['method'], $request->method())) {
724
                return false;
725
            }
726
        }
727
728
        // AJAX PJAX 请求检查
729
        foreach (['ajax', 'pjax', 'json'] as $item) {
730
            if (isset($option[$item])) {
731
                $call = 'is' . $item;
732
                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...
733
                    return false;
734
                }
735
            }
736
        }
737
738
        // 伪静态后缀检测
739
        if ($request->url() != '/' && ((isset($option['ext']) && false === stripos('|' . $option['ext'] . '|', '|' . $request->ext() . '|'))
740
            || (isset($option['deny_ext']) && false !== stripos('|' . $option['deny_ext'] . '|', '|' . $request->ext() . '|')))) {
0 ignored issues
show
Coding Style introduced by
Closing parenthesis of a multi-line IF statement must be on a new line
Loading history...
741
            return false;
742
        }
743
744
        // 域名检查
745
        if ((isset($option['domain']) && !in_array($option['domain'], [$request->host(true), $request->subDomain()]))) {
746
            return false;
747
        }
748
749
        // HTTPS检查
750
        if ((isset($option['https']) && $option['https'] && !$request->isSsl())
751
            || (isset($option['https']) && !$option['https'] && $request->isSsl())) {
0 ignored issues
show
Coding Style introduced by
Closing parenthesis of a multi-line IF statement must be on a new line
Loading history...
752
            return false;
753
        }
754
755
        // 请求参数检查
756
        if (isset($option['filter'])) {
757
            foreach ($option['filter'] as $name => $value) {
758
                if ($request->param($name, '', null) != $value) {
759
                    return false;
760
                }
761
            }
762
        }
763
764
        return true;
765
    }
766
767
    /**
0 ignored issues
show
Coding Style introduced by
Parameter $url should have a doc-comment as per coding-style.
Loading history...
768
     * 解析URL地址中的参数Request对象
769
     * @access protected
770
     * @param  string $rule 路由规则
0 ignored issues
show
Coding Style introduced by
Doc comment for parameter $rule does not match actual variable name $url
Loading history...
771
     * @param  array  $var 变量
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 1 found
Loading history...
772
     * @return void
773
     */
774
    protected function parseUrlParams(string $url, array &$var = []): void
775
    {
776
        if ($url) {
777
            preg_replace_callback('/(\w+)\|([^\|]+)/', function ($match) use (&$var) {
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
778
                $var[$match[1]] = strip_tags($match[2]);
779
            }, $url);
0 ignored issues
show
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
780
        }
781
    }
782
783
    /**
784
     * 解析URL的pathinfo参数
785
     * @access public
786
     * @param  string $url URL地址
787
     * @return array
788
     */
789
    public function parseUrlPath(string $url): array
790
    {
791
        // 分隔符替换 确保路由定义使用统一的分隔符
792
        $url = str_replace('|', '/', $url);
793
        $url = trim($url, '/');
794
795
        if (strpos($url, '/')) {
796
            // [控制器/操作]
797
            $path = explode('/', $url);
798
        } else {
799
            $path = [$url];
800
        }
801
802
        return $path;
803
    }
804
805
    /**
806
     * 生成路由的正则规则
807
     * @access protected
808
     * @param  string $rule 路由规则
0 ignored issues
show
Coding Style introduced by
Expected 10 spaces after parameter name; 1 found
Loading history...
809
     * @param  array  $match 匹配的变量
0 ignored issues
show
Coding Style introduced by
Expected 9 spaces after parameter name; 1 found
Loading history...
810
     * @param  array  $pattern   路由变量规则
0 ignored issues
show
Coding Style introduced by
Expected 7 spaces after parameter name; 3 found
Loading history...
811
     * @param  array  $option    路由参数
0 ignored issues
show
Coding Style introduced by
Expected 8 spaces after parameter name; 4 found
Loading history...
812
     * @param  bool   $completeMatch   路由是否完全匹配
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 3 found
Loading history...
813
     * @param  string $suffix   路由正则变量后缀
0 ignored issues
show
Coding Style introduced by
Expected 8 spaces after parameter name; 3 found
Loading history...
814
     * @return string
815
     */
816
    protected function buildRuleRegex(string $rule, array $match, array $pattern = [], array $option = [], bool $completeMatch = false, string $suffix = ''): string
817
    {
818
        foreach ($match as $name) {
819
            $replace[] = $this->buildNameRegex($name, $pattern, $suffix);
820
        }
821
822
        // 是否区分 / 地址访问
823
        if ('/' != $rule) {
824
            if (!empty($option['remove_slash'])) {
825
                $rule = rtrim($rule, '/');
826
            } elseif (substr($rule, -1) == '/') {
827
                $rule     = rtrim($rule, '/');
828
                $hasSlash = true;
829
            }
830
        }
831
832
        $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 818. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
833
        $regex = str_replace([')?/', ')/', ')?-', ')-', '\\\\/'], [')\/', ')\/', ')\-', ')\-', '\/'], $regex);
834
835
        if (isset($hasSlash)) {
836
            $regex .= '\/';
837
        }
838
839
        return $regex . ($completeMatch ? '$' : '');
840
    }
841
842
    /**
843
     * 生成路由变量的正则规则
844
     * @access protected
845
     * @param  string $name    路由变量
846
     * @param  array  $pattern 变量规则
847
     * @param  string $suffix  路由正则变量后缀
848
     * @return string
849
     */
850
    protected function buildNameRegex(string $name, array $pattern, string $suffix): string
851
    {
852
        $optional = '';
853
        $slash    = substr($name, 0, 1);
854
855
        if (in_array($slash, ['/', '-'])) {
856
            $prefix = '\\' . $slash;
857
            $name   = substr($name, 1);
858
            $slash  = substr($name, 0, 1);
859
        } else {
860
            $prefix = '';
861
        }
862
863
        if ('<' != $slash) {
864
            return $prefix . preg_quote($name, '/');
865
        }
866
867
        if (strpos($name, '?')) {
868
            $name     = substr($name, 1, -2);
869
            $optional = '?';
870
        } elseif (strpos($name, '>')) {
871
            $name = substr($name, 1, -1);
872
        }
873
874
        if (isset($pattern[$name])) {
875
            $nameRule = $pattern[$name];
876
            if (0 === strpos($nameRule, '/') && '/' == substr($nameRule, -1)) {
877
                $nameRule = substr($nameRule, 1, -1);
878
            }
879
        } else {
880
            $nameRule = $this->router->config('default_route_pattern');
881
        }
882
883
        return '(' . $prefix . '(?<' . $name . $suffix . '>' . $nameRule . '))' . $optional;
884
    }
885
886
    /**
887
     * 设置路由参数
888
     * @access public
889
     * @param  string $method 方法名
890
     * @param  array  $args   调用参数
891
     * @return $this
892
     */
893
    public function __call($method, $args)
894
    {
895
        if (count($args) > 1) {
896
            $args[0] = $args;
897
        }
898
        array_unshift($args, $method);
899
900
        return call_user_func_array([$this, 'setOption'], $args);
901
    }
902
903
    public function __sleep()
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function __sleep()
Loading history...
904
    {
905
        return ['name', 'rule', 'route', 'method', 'vars', 'option', 'pattern'];
906
    }
907
908
    public function __wakeup()
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function __wakeup()
Loading history...
909
    {
910
        $this->router = Container::pull('route');
911
    }
912
913
    public function __debugInfo()
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function __debugInfo()
Loading history...
914
    {
915
        return [
916
            'name'    => $this->name,
917
            'rule'    => $this->rule,
918
            'route'   => $this->route,
919
            'method'  => $this->method,
920
            'vars'    => $this->vars,
921
            'option'  => $this->option,
922
            'pattern' => $this->pattern,
923
        ];
924
    }
925
}
926