Passed
Push — 5.2 ( ead1b1...98d507 )
by liu
02:32
created

Rule   F

Complexity

Total Complexity 139

Size/Duplication

Total Lines 993
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 246
dl 0
loc 993
rs 2
c 0
b 0
f 0
wmc 139

57 Methods

Rating   Name   Duplication   Size   Complexity  
A config() 0 3 1
A option() 0 5 1
A getParent() 0 3 1
A getRouter() 0 3 1
A getVars() 0 3 1
A getRule() 0 3 1
A getDomain() 0 3 1
A pattern() 0 5 1
A setOption() 0 5 1
A getRoute() 0 3 1
A getPattern() 0 7 2
A name() 0 5 1
A getName() 0 3 1
A method() 0 3 1
A getMethod() 0 3 1
A doAfter() 0 3 1
A getOption() 0 7 2
A model() 0 13 4
A depr() 0 3 1
A response() 0 4 1
A append() 0 5 1
A mergeOptions() 0 4 1
A cache() 0 3 1
A header() 0 5 1
A middleware() 0 11 4
A filter() 0 5 1
A ext() 0 3 1
A denyExt() 0 3 1
A domain() 0 3 1
A https() 0 3 1
A validate() 0 5 1
A view() 0 3 1
A dispatchMethod() 0 8 2
A removeSlash() 0 3 1
B buildRuleRegex() 0 24 7
A allowCrossDomain() 0 11 4
A parseRule() 0 34 6
A parseUrlPath() 0 24 4
A redirect() 0 3 1
B dispatch() 0 23 11
A crossDomainRule() 0 11 2
A parseUrlParams() 0 6 2
A completeMatch() 0 3 1
A mergeGroupOptions() 0 13 4
A dispatchController() 0 9 2
A status() 0 3 1
A __debugInfo() 0 10 1
A __wakeup() 0 3 1
A ajax() 0 3 1
A __sleep() 0 3 1
A __call() 0 8 2
A pjax() 0 3 1
D checkOption() 0 46 26
A checkCrossDomain() 0 18 4
A parseVar() 0 21 5
B buildNameRegex() 0 34 8
A json() 0 3 1

How to fix   Complexity   

Complex Class

Complex classes like Rule often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Rule, and based on these observations, apply Extract Interface, too.

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