Completed
Push — 6.0 ( f72017...dd4125 )
by liu
02:52
created

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