Passed
Push — 8.0 ( efb207...1ced43 )
by liu
02:33
created

Rule::setOption()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

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

675
            if (str_contains($value, /** @scrutinizer ignore-type */ $depr)) {
Loading history...
676
                $extraParams = false;
677
            }
678
        }
679
680 24
        if (is_string($route)) {
681 9
            $route = str_replace($search, $replace, $route);
682
        }
683
684
        // 解析额外参数
685 24
        if ($extraParams) {
686 24
            $count = substr_count($rule, '/');
687 24
            $url   = array_slice(explode('|', $url), $count + 1);
688 24
            $this->parseUrlParams(implode('|', $url), $matches);
689
        }
690
691 24
        foreach ($matches as $key => &$val) {
692
            if (isset($this->pattern[$key]) && in_array($this->pattern[$key], ['\d+', 'int', 'float'])) {
693
                $val = match ($this->pattern[$key]) {
694
                    'int', '\d+' => (int) $val,
695
                    'float'      => (float) $val,
696
                    default      => $val,
697
                };
698
            }
699
        }
700
701 24
        $this->vars = $matches;
702
703
        // 发起路由调度
704 24
        return $this->dispatch($request, $route, $option);
705
    }
706
707
    /**
708
     * 发起路由调度
709
     * @access protected
710
     * @param  Request $request Request对象
711
     * @param  mixed   $route  路由地址
712
     * @param  array   $option 路由参数
713
     * @return Dispatch
714
     */
715 24
    protected function dispatch(Request $request, $route, array $option): Dispatch
716
    {
717 24
        if (isset($option['dispatcher']) && is_subclass_of($option['dispatcher'], Dispatch::class)) {
718
            // 指定分组的调度处理对象
719
            $result = new $option['dispatcher']($request, $this, $route, $this->vars, $option);
720 24
        } elseif (is_subclass_of($route, Dispatch::class)) {
721
            $result = new $route($request, $this, $route, $this->vars, $option);
722 24
        } elseif ($route instanceof Closure) {
723
            // 执行闭包
724 15
            $result = new CallbackDispatch($request, $this, $route, $this->vars, $option);
725 9
        } elseif (is_array($route)) {
726
            // 路由到类的方法
727
            $result = $this->dispatchMethod($request, $route, $option);
728 9
        } elseif (str_contains($route, '@') || str_contains($route, '::') || str_contains($route, '\\')) {
729
            // 路由到类的方法
730
            $route  = str_replace('::', '@', $route);
731
            $result = $this->dispatchMethod($request, $route, $option);
732
        } else {
733
            // 路由到控制器/操作
734 9
            $result = $this->dispatchController($request, $route, $option);
735
        }
736
737 24
        return $result;
738
    }
739
740
    /**
741
     * 调度到类的方法
742
     * @access protected
743
     * @param  Request $request Request对象
744
     * @param  string|array  $route 路由地址
745
     * @return CallbackDispatch
746
     */
747
    protected function dispatchMethod(Request $request, string | array $route, array $option = []): CallbackDispatch
748
    {
749
        if (is_string($route)) {
0 ignored issues
show
introduced by
The condition is_string($route) is always false.
Loading history...
750
            $path = $this->parseUrlPath($route);
751
752
            $route  = str_replace('/', '@', implode('/', $path));
753
            $method = str_contains($route, '@') ? explode('@', $route) : $route;
754
        } else {
755
            $method = $route;
756
        }
757
758
        return new CallbackDispatch($request, $this, $method, $this->vars, $option);
759
    }
760
761
    /**
762
     * 调度到控制器方法 规则:模块/控制器/操作
763
     * @access protected
764
     * @param  Request $request Request对象
765
     * @param  string  $route 路由地址
766
     * @return ControllerDispatch
767
     */
768 9
    protected function dispatchController(Request $request, string $route, array $option = []): ControllerDispatch
769
    {
770 9
        $path = $this->parseUrlPath($route);
771
772 9
        $action     = array_pop($path);
773 9
        $controller = !empty($path) ? array_pop($path) : null;
774
775
        // 路由到模块/控制器/操作
776 9
        return new ControllerDispatch($request, $this, [$controller, $action], $this->vars, $option);
777
    }
778
779
    /**
780
     * 路由检查
781
     * @access protected
782
     * @param  array   $option 路由参数
783
     * @param  Request $request Request对象
784
     * @return bool
785
     */
786 27
    protected function checkOption(array $option, Request $request): bool
787
    {
788
        // 检查当前路由是否匹配
789 27
        if (isset($option['match']) && is_callable($option['match'])) {
790
            if (false === $option['match']($this, $request)) {
791
                return false;
792
            }
793
        }
794
795
        // 请求类型检测
796 27
        if (!empty($option['method'])) {
797
            if (is_string($option['method']) && false === stripos($option['method'], $request->method())) {
798
                return false;
799
            }
800
        }
801
802
        // AJAX PJAX 请求检查
803 27
        foreach (['ajax', 'pjax', 'json'] as $item) {
804 27
            if (isset($option[$item])) {
805
                $call = 'is' . $item;
806
                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...
807
                    return false;
808
                }
809
            }
810
        }
811
812
        // 伪静态后缀检测
813 27
        if ($request->url() != '/' && ((isset($option['ext']) && false === stripos('|' . $option['ext'] . '|', '|' . $request->ext() . '|'))
814 27
            || (isset($option['deny_ext']) && false !== stripos('|' . $option['deny_ext'] . '|', '|' . $request->ext() . '|')))) {
815
            return false;
816
        }
817
818
        // 域名检查
819 27
        if ((isset($option['domain']) && !in_array($option['domain'], [$request->host(true), $request->subDomain()]))) {
820
            return false;
821
        }
822
823
        // HTTPS检查
824 27
        if ((isset($option['https']) && $option['https'] && !$request->isSsl())
825 27
            || (isset($option['https']) && !$option['https'] && $request->isSsl())
826
        ) {
827
            return false;
828
        }
829
830
        // 请求参数检查
831 27
        if (isset($option['filter'])) {
832
            foreach ($option['filter'] as $name => $value) {
833
                if ($request->param($name, '') != $value) {
834
                    return false;
835
                }
836
            }
837
        }
838
839 27
        return true;
840
    }
841
842
    /**
843
     * 解析URL地址中的参数Request对象
844
     * @access protected
845
     * @param  string $rule 路由规则
846
     * @param  array  $var 变量
847
     * @return void
848
     */
849 24
    protected function parseUrlParams(string $url, array &$var = []): void
850
    {
851 24
        if ($url) {
852
            preg_replace_callback('/(\w+)\|([^\|]+)/', function ($match) use (&$var) {
853
                $var[$match[1]] = strip_tags($match[2]);
854
            }, $url);
855
        }
856
    }
857
858
    /**
859
     * 解析URL的pathinfo参数
860
     * @access public
861
     * @param  string $url URL地址
862
     * @return array
863
     */
864 12
    public function parseUrlPath(string $url): array
865
    {
866
        // 分隔符替换 确保路由定义使用统一的分隔符
867 12
        $url = str_replace('|', '/', $url);
868 12
        $url = trim($url, '/');
869
870 12
        if (str_contains($url, '/')) {
871
            // [控制器/操作]
872 9
            $path = explode('/', $url);
873
        } else {
874 3
            $path = [$url];
875
        }
876
877 12
        return $path;
878
    }
879
880
    /**
881
     * 生成路由的正则规则
882
     * @access protected
883
     * @param  string $rule 路由规则
884
     * @param  array  $match 匹配的变量
885
     * @param  array  $pattern   路由变量规则
886
     * @param  array  $option    路由参数
887
     * @param  bool   $completeMatch   路由是否完全匹配
888
     * @param  string $suffix   路由正则变量后缀
889
     * @return string
890
     */
891
    protected function buildRuleRegex(string $rule, array $match, array $pattern = [], array $option = [], bool $completeMatch = false, string $suffix = ''): string
892
    {
893
        foreach ($match as $name) {
894
            $value = $this->buildNameRegex($name, $pattern, $suffix);
895
            if ($value) {
896
                $origin[]  = $name;
897
                $replace[] = $value;
898
            }
899
        }
900
901
        // 是否区分 / 地址访问
902
        if ('/' != $rule) {
903
            if (!empty($option['remove_slash'])) {
904
                $rule = rtrim($rule, '/');
905
            } elseif (str_ends_with($rule, '/')) {
906
                $rule     = rtrim($rule, '/');
907
                $hasSlash = true;
908
            }
909
        }
910
911
        $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...
912
        $regex = str_replace([')?/', ')?-'], [')/', ')-'], $regex);
913
914
        if (isset($hasSlash)) {
915
            $regex .= '/';
916
        }
917
918
        return $regex . ($completeMatch ? '$' : '');
919
    }
920
921
    /**
922
     * 生成路由变量的正则规则
923
     * @access protected
924
     * @param  string $name    路由变量
925
     * @param  array  $pattern 变量规则
926
     * @param  string $suffix  路由正则变量后缀
927
     * @return string
928
     */
929
    protected function buildNameRegex(string $name, array $pattern, string $suffix): string
930
    {
931
        $optional = '';
932
        $slash    = substr($name, 0, 1);
933
934
        if (in_array($slash, ['/', '-'])) {
935
            $prefix = $slash;
936
            $name   = substr($name, 1);
937
            $slash  = substr($name, 0, 1);
938
        } else {
939
            $prefix = '';
940
        }
941
942
        if ('<' != $slash) {
943
            return '';
944
        }
945
946
        if (str_contains($name, '?')) {
947
            $name     = substr($name, 1, -2);
948
            $optional = '?';
949
        } elseif (str_contains($name, '>')) {
950
            $name = substr($name, 1, -1);
951
        }
952
953
        if (isset($pattern[$name])) {
954
            $nameRule = $pattern[$name];
955
            if (isset($this->regex[$nameRule])) {
956
                $nameRule = $this->regex[$nameRule];
957
            }
958
959
            if (str_starts_with($nameRule, '/') && str_ends_with($nameRule, '/')) {
960
                $nameRule = substr($nameRule, 1, -1);
961
            }
962
        } else {
963
            $nameRule = $this->config('default_route_pattern');
964
        }
965
966
        return '(' . $prefix . '(?<' . $name . $suffix . '>' . $nameRule . '))' . $optional;
967
    }
968
969
    /**
970
     * 设置路由参数
971
     * @access public
972
     * @param  string $method 方法名
973
     * @param  array  $args   调用参数
974
     * @return $this
975
     */
976
    public function __call($method, $args)
977
    {
978
        if (count($args) > 1) {
979
            $args[0] = $args;
980
        }
981
        array_unshift($args, $method);
982
983
        return call_user_func_array([$this, 'setOption'], $args);
984
    }
985
986
    public function __sleep()
987
    {
988
        return ['name', 'rule', 'route', 'method', 'vars', 'option', 'pattern'];
989
    }
990
991
    public function __wakeup()
992
    {
993
        $this->router = Container::pull('route');
994
    }
995
996
    public function __debugInfo()
997
    {
998
        return [
999
            'name'    => $this->name,
1000
            'rule'    => $this->rule,
1001
            'route'   => $this->route,
1002
            'method'  => $this->method,
1003
            'vars'    => $this->vars,
1004
            'option'  => $this->option,
1005
            'pattern' => $this->pattern,
1006
        ];
1007
    }
1008
}
1009