Passed
Pull Request — 5.1 (#1748)
by guanguans
09:27
created

RuleGroup::only()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
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~2018 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
12
namespace think\route;
13
14
use think\Container;
15
use think\Exception;
16
use think\Request;
17
use think\Response;
18
use think\Route;
19
use think\route\dispatch\Response as ResponseDispatch;
20
use think\route\dispatch\Url as UrlDispatch;
21
22
class RuleGroup extends Rule
1 ignored issue
show
Coding Style introduced by
Missing class doc comment
Loading history...
23
{
24
    // 分组路由(包括子分组)
25
    protected $rules = [
26
        '*'       => [],
27
        'get'     => [],
28
        'post'    => [],
29
        'put'     => [],
30
        'patch'   => [],
31
        'delete'  => [],
32
        'head'    => [],
33
        'options' => [],
34
    ];
35
36
    // MISS路由
37
    protected $miss;
38
39
    // 自动路由
40
    protected $auto;
41
42
    // 完整名称
43
    protected $fullName;
44
45
    // 所在域名
46
    protected $domain;
47
48
    /**
49
     * 架构函数
50
     * @access public
51
     * @param  Route       $router   路由对象
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 3 found
Loading history...
52
     * @param  RuleGroup   $parent   上级对象
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 3 found
Loading history...
53
     * @param  string      $name     分组名称
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 5 found
Loading history...
54
     * @param  mixed       $rule     分组路由
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 5 found
Loading history...
55
     * @param  array       $option   路由参数
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 3 found
Loading history...
56
     * @param  array       $pattern  变量规则
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 2 found
Loading history...
57
     */
58
    public function __construct(Route $router, RuleGroup $parent = null, $name = '', $rule = [], $option = [], $pattern = [])
59
    {
60
        $this->router  = $router;
0 ignored issues
show
Documentation Bug introduced by
It seems like $router of type think\Route is incompatible with the declared type think\route\Route of property $router.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
61
        $this->parent  = $parent;
62
        $this->rule    = $rule;
63
        $this->name    = trim($name, '/');
64
        $this->option  = $option;
65
        $this->pattern = $pattern;
66
67
        $this->setFullName();
68
69
        if ($this->parent) {
70
            $this->domain = $this->parent->getDomain();
71
            $this->parent->addRuleItem($this);
72
        }
73
74
        if (!empty($option['cross_domain'])) {
75
            $this->router->setCrossDomainRule($this);
76
        }
77
78
        if ($router->isTest()) {
79
            $this->lazy(false);
80
        }
81
    }
82
83
    /**
84
     * 设置分组的路由规则
85
     * @access public
86
     * @return void
87
     */
88
    protected function setFullName()
89
    {
90
        if (false !== strpos($this->name, ':')) {
91
            $this->name = preg_replace(['/\[\:(\w+)\]/', '/\:(\w+)/'], ['<\1?>', '<\1>'], $this->name);
92
        }
93
94
        if ($this->parent && $this->parent->getFullName()) {
95
            $this->fullName = $this->parent->getFullName() . ($this->name ? '/' . $this->name : '');
96
        } else {
97
            $this->fullName = $this->name;
98
        }
99
    }
100
101
    /**
102
     * 获取所属域名
103
     * @access public
104
     * @return string
105
     */
106
    public function getDomain()
107
    {
108
        return $this->domain;
109
    }
110
111
    /**
112
     * 检测分组路由
113
     * @access public
114
     * @param  Request      $request  请求对象
0 ignored issues
show
Coding Style introduced by
Expected 7 spaces after parameter name; 2 found
Loading history...
115
     * @param  string       $url      访问地址
0 ignored issues
show
Coding Style introduced by
Expected 11 spaces after parameter name; 6 found
Loading history...
116
     * @param  bool         $completeMatch   路由是否完全匹配
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 3 found
Loading history...
117
     * @return Dispatch|false
118
     */
119
    public function check($request, $url, $completeMatch = false)
120
    {
121
        if ($dispatch = $this->checkCrossDomain($request)) {
122
            // 跨域OPTIONS请求
123
            return $dispatch;
124
        }
125
126
        // 检查分组有效性
127
        if (!$this->checkOption($this->option, $request) || !$this->checkUrl($url)) {
128
            return false;
129
        }
130
131
        // 检查前置行为
132
        if (isset($this->option['before'])) {
133
            if (false === $this->checkBefore($this->option['before'])) {
134
                return false;
135
            }
136
            unset($this->option['before']);
137
        }
138
139
        // 解析分组路由
140
        if ($this instanceof Resource) {
141
            $this->buildResourceRule();
142
        } elseif ($this->rule) {
143
            if ($this->rule instanceof Response) {
144
                return new ResponseDispatch($request, $this, $this->rule);
145
            }
146
147
            $this->parseGroupRule($this->rule);
148
        }
149
150
        // 获取当前路由规则
151
        $method = strtolower($request->method());
152
        $rules  = $this->getMethodRules($method);
153
154
        if ($this->parent) {
155
            // 合并分组参数
156
            $this->mergeGroupOptions();
157
            // 合并分组变量规则
158
            $this->pattern = array_merge($this->parent->getPattern(), $this->pattern);
159
        }
160
161
        if (isset($this->option['complete_match'])) {
162
            $completeMatch = $this->option['complete_match'];
163
        }
164
165
        if (!empty($this->option['merge_rule_regex'])) {
166
            // 合并路由正则规则进行路由匹配检查
167
            $result = $this->checkMergeRuleRegex($request, $rules, $url, $completeMatch);
168
169
            if (false !== $result) {
170
                return $result;
171
            }
172
        }
173
174
        // 检查分组路由
175
        foreach ($rules as $key => $item) {
176
            $result = $item->check($request, $url, $completeMatch);
177
178
            if (false !== $result) {
179
                return $result;
180
            }
181
        }
182
183
        if ($this->auto) {
184
            // 自动解析URL地址
185
            $result = new UrlDispatch($request, $this, $this->auto . '/' . $url, ['auto_search' => false]);
186
        } elseif ($this->miss && in_array($this->miss->getMethod(), ['*', $method])) {
187
            // 未匹配所有路由的路由规则处理
188
            $result = $this->miss->parseRule($request, '', $this->miss->getRoute(), $url, $this->miss->mergeGroupOptions());
189
        } else {
190
            $result = false;
191
        }
192
193
        return $result;
194
    }
195
196
    /**
197
     * 获取当前请求的路由规则(包括子分组、资源路由)
198
     * @access protected
199
     * @param  string      $method
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
200
     * @return array
201
     */
202
    protected function getMethodRules($method)
203
    {
204
        return array_merge($this->rules[$method], $this->rules['*']);
205
    }
206
207
    /**
208
     * 分组URL匹配检查
209
     * @access protected
210
     * @param  string     $url
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
211
     * @return bool
212
     */
213
    protected function checkUrl($url)
214
    {
215
        if ($this->fullName) {
216
            $pos = strpos($this->fullName, '<');
217
218
            if (false !== $pos) {
219
                $str = substr($this->fullName, 0, $pos);
220
            } else {
221
                $str = $this->fullName;
222
            }
223
224
            if ($str && 0 !== stripos(str_replace('|', '/', $url), $str)) {
225
                return false;
226
            }
227
        }
228
229
        return true;
230
    }
231
232
    /**
233
     * 延迟解析分组的路由规则
234
     * @access public
235
     * @param  bool     $lazy   路由是否延迟解析
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 3 found
Loading history...
236
     * @return $this
237
     */
238
    public function lazy($lazy = true)
239
    {
240
        if (!$lazy) {
241
            $this->parseGroupRule($this->rule);
242
            $this->rule = null;
243
        }
244
245
        return $this;
246
    }
247
248
    /**
249
     * 解析分组和域名的路由规则及绑定
250
     * @access public
251
     * @param  mixed        $rule    路由规则
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 4 found
Loading history...
252
     * @return void
253
     */
254
    public function parseGroupRule($rule)
255
    {
256
        $origin = $this->router->getGroup();
257
        $this->router->setGroup($this);
258
259
        if ($rule instanceof \Closure) {
260
            Container::getInstance()->invokeFunction($rule);
261
        } elseif (is_array($rule)) {
262
            $this->addRules($rule);
263
        } elseif (is_string($rule) && $rule) {
264
            $this->router->bind($rule, $this->domain);
265
        }
266
267
        $this->router->setGroup($origin);
268
    }
269
270
    /**
271
     * 检测分组路由
272
     * @access public
273
     * @param  Request      $request  请求对象
0 ignored issues
show
Coding Style introduced by
Expected 7 spaces after parameter name; 2 found
Loading history...
274
     * @param  array        $rules    路由规则
0 ignored issues
show
Coding Style introduced by
Expected 9 spaces after parameter name; 4 found
Loading history...
275
     * @param  string       $url      访问地址
0 ignored issues
show
Coding Style introduced by
Expected 11 spaces after parameter name; 6 found
Loading history...
276
     * @param  bool         $completeMatch   路由是否完全匹配
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 3 found
Loading history...
277
     * @return Dispatch|false
278
     */
279
    protected function checkMergeRuleRegex($request, &$rules, $url, $completeMatch)
280
    {
281
        $depr = $this->router->config('pathinfo_depr');
282
        $url  = $depr . str_replace('|', $depr, $url);
283
284
        foreach ($rules as $key => $item) {
285
            if ($item instanceof RuleItem) {
286
                $rule = $depr . str_replace('/', $depr, $item->getRule());
287
                if ($depr == $rule && $depr != $url) {
288
                    unset($rules[$key]);
289
                    continue;
290
                }
291
292
                $complete = null !== $item->getOption('complete_match') ? $item->getOption('complete_match') : $completeMatch;
293
294
                if (false === strpos($rule, '<')) {
295
                    if (0 === strcasecmp($rule, $url) || (!$complete && 0 === strncasecmp($rule, $url, strlen($rule)))) {
296
                        return $item->checkRule($request, $url, []);
297
                    }
298
299
                    unset($rules[$key]);
300
                    continue;
301
                }
302
303
                $slash = preg_quote('/-' . $depr, '/');
304
305
                if ($matchRule = preg_split('/[' . $slash . ']<\w+\??>/', $rule, 2)) {
306
                    if ($matchRule[0] && 0 !== strncasecmp($rule, $url, strlen($matchRule[0]))) {
307
                        unset($rules[$key]);
308
                        continue;
309
                    }
310
                }
311
312
                if (preg_match_all('/[' . $slash . ']?<?\w+\??>?/', $rule, $matches)) {
313
                    unset($rules[$key]);
314
                    $pattern = array_merge($this->getPattern(), $item->getPattern());
315
                    $option  = array_merge($this->getOption(), $item->getOption());
316
317
                    $regex[$key] = $this->buildRuleRegex($rule, $matches[0], $pattern, $option, $complete, '_THINK_' . $key);
318
                    $items[$key] = $item;
319
                }
320
            }
321
        }
322
323
        if (empty($regex)) {
324
            return false;
325
        }
326
327
        try {
328
            $result = preg_match('/^(?:' . implode('|', $regex) . ')/u', $url, $match);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $regex does not seem to be defined for all execution paths leading up to this point.
Loading history...
329
        } catch (\Exception $e) {
330
            throw new Exception('route pattern error');
331
        }
332
333
        if ($result) {
334
            $var = [];
335
            foreach ($match as $key => $val) {
336
                if (is_string($key) && '' !== $val) {
337
                    list($name, $pos) = explode('_THINK_', $key);
338
339
                    $var[$name] = $val;
340
                }
341
            }
342
343
            if (!isset($pos)) {
344
                foreach ($regex as $key => $item) {
345
                    if (0 === strpos(str_replace(['\/', '\-', '\\' . $depr], ['/', '-', $depr], $item), $match[0])) {
346
                        $pos = $key;
347
                        break;
348
                    }
349
                }
350
            }
351
352
            $rule  = $items[$pos]->getRule();
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $items does not seem to be defined for all execution paths leading up to this point.
Loading history...
Comprehensibility Best Practice introduced by
The variable $pos does not seem to be defined for all execution paths leading up to this point.
Loading history...
353
            $array = $this->router->getRule($rule);
354
355
            foreach ($array as $item) {
356
                if (in_array($item->getMethod(), ['*', strtolower($request->method())])) {
357
                    $result = $item->checkRule($request, $url, $var);
358
359
                    if (false !== $result) {
360
                        return $result;
361
                    }
362
                }
363
            }
364
        }
365
366
        return false;
367
    }
368
369
    /**
370
     * 获取分组的MISS路由
371
     * @access public
372
     * @return RuleItem|null
373
     */
374
    public function getMissRule()
375
    {
376
        return $this->miss;
377
    }
378
379
    /**
380
     * 获取分组的自动路由
381
     * @access public
382
     * @return string
383
     */
384
    public function getAutoRule()
385
    {
386
        return $this->auto;
387
    }
388
389
    /**
390
     * 注册自动路由
391
     * @access public
392
     * @param  string     $route   路由规则
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 3 found
Loading history...
393
     * @return void
394
     */
395
    public function addAutoRule($route)
396
    {
397
        $this->auto = $route;
398
    }
399
400
    /**
401
     * 注册MISS路由
402
     * @access public
403
     * @param  string    $route      路由地址
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 6 found
Loading history...
404
     * @param  string    $method     请求类型
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 5 found
Loading history...
405
     * @param  array     $option     路由参数
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 5 found
Loading history...
406
     * @return RuleItem
407
     */
408
    public function addMissRule($route, $method = '*', $option = [])
409
    {
410
        // 创建路由规则实例
411
        $ruleItem = new RuleItem($this->router, $this, null, '', $route, strtolower($method), $option);
412
413
        $this->miss = $ruleItem;
414
415
        return $ruleItem;
416
    }
417
418
    /**
419
     * 添加分组下的路由规则或者子分组
420
     * @access public
421
     * @param  string    $rule       路由规则
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 7 found
Loading history...
422
     * @param  string    $route      路由地址
0 ignored issues
show
Coding Style introduced by
Expected 3 spaces after parameter name; 6 found
Loading history...
423
     * @param  string    $method     请求类型
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 5 found
Loading history...
424
     * @param  array     $option     路由参数
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 5 found
Loading history...
425
     * @param  array     $pattern    变量规则
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 4 found
Loading history...
426
     * @return $this
427
     */
428
    public function addRule($rule, $route, $method = '*', $option = [], $pattern = [])
429
    {
430
        // 读取路由标识
431
        if (is_array($rule)) {
0 ignored issues
show
introduced by
The condition is_array($rule) is always false.
Loading history...
432
            $name = $rule[0];
433
            $rule = $rule[1];
434
        } elseif (is_string($route)) {
0 ignored issues
show
introduced by
The condition is_string($route) is always true.
Loading history...
435
            $name = $route;
436
        } else {
437
            $name = null;
438
        }
439
440
        $method = strtolower($method);
441
442
        if ('/' === $rule || '' === $rule) {
443
            // 首页自动完整匹配
444
            $rule .= '$';
445
        }
446
447
        // 创建路由规则实例
448
        $ruleItem = new RuleItem($this->router, $this, $name, $rule, $route, $method, $option, $pattern);
449
450
        if (!empty($option['cross_domain'])) {
451
            $this->router->setCrossDomainRule($ruleItem, $method);
452
        }
453
454
        $this->addRuleItem($ruleItem, $method);
455
456
        return $ruleItem;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $ruleItem returns the type think\route\RuleItem which is incompatible with the documented return type think\route\RuleGroup.
Loading history...
457
    }
458
459
    /**
460
     * 批量注册路由规则
461
     * @access public
462
     * @param  array     $rules      路由规则
0 ignored issues
show
Coding Style introduced by
Expected 3 spaces after parameter name; 6 found
Loading history...
463
     * @param  string    $method     请求类型
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 5 found
Loading history...
464
     * @param  array     $option     路由参数
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 5 found
Loading history...
465
     * @param  array     $pattern    变量规则
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 4 found
Loading history...
466
     * @return void
467
     */
468
    public function addRules($rules, $method = '*', $option = [], $pattern = [])
469
    {
470
        foreach ($rules as $key => $val) {
471
            if (is_numeric($key)) {
472
                $key = array_shift($val);
473
            }
474
475
            if (is_array($val)) {
476
                $route   = array_shift($val);
477
                $option  = $val ? array_shift($val) : [];
478
                $pattern = $val ? array_shift($val) : [];
479
            } else {
480
                $route = $val;
481
            }
482
483
            $this->addRule($key, $route, $method, $option, $pattern);
484
        }
485
    }
486
487
    public function addRuleItem($rule, $method = '*')
0 ignored issues
show
Coding Style introduced by
Missing function doc comment
Loading history...
488
    {
489
        if (strpos($method, '|')) {
490
            $rule->method($method);
491
            $method = '*';
492
        }
493
494
        $this->rules[$method][] = $rule;
495
496
        return $this;
497
    }
498
499
    /**
500
     * 设置分组的路由前缀
501
     * @access public
502
     * @param  string     $prefix
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
503
     * @return $this
504
     */
505
    public function prefix($prefix)
506
    {
507
        if ($this->parent && $this->parent->getOption('prefix')) {
508
            $prefix = $this->parent->getOption('prefix') . $prefix;
509
        }
510
511
        return $this->option('prefix', $prefix);
512
    }
513
514
    /**
515
     * 设置资源允许
516
     * @access public
517
     * @param  array     $only
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
518
     * @return $this
519
     */
520
    public function only($only)
521
    {
522
        return $this->option('only', $only);
523
    }
524
525
    /**
526
     * 设置资源排除
527
     * @access public
528
     * @param  array     $except
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
529
     * @return $this
530
     */
531
    public function except($except)
532
    {
533
        return $this->option('except', $except);
534
    }
535
536
    /**
537
     * 设置资源路由的变量
538
     * @access public
539
     * @param  array     $vars
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
540
     * @return $this
541
     */
542
    public function vars($vars)
543
    {
544
        return $this->option('var', $vars);
545
    }
546
547
    /**
548
     * 合并分组的路由规则正则
549
     * @access public
550
     * @param  bool     $merge
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
551
     * @return $this
552
     */
553
    public function mergeRuleRegex($merge = true)
554
    {
555
        return $this->option('merge_rule_regex', $merge);
556
    }
557
558
    /**
559
     * 获取完整分组Name
560
     * @access public
561
     * @return string
562
     */
563
    public function getFullName()
564
    {
565
        return $this->fullName;
566
    }
567
568
    /**
569
     * 获取分组的路由规则
570
     * @access public
571
     * @param  string     $method
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
572
     * @return array
573
     */
574
    public function getRules($method = '')
575
    {
576
        if ('' === $method) {
577
            return $this->rules;
578
        }
579
580
        return isset($this->rules[strtolower($method)]) ? $this->rules[strtolower($method)] : [];
581
    }
582
583
    /**
584
     * 清空分组下的路由规则
585
     * @access public
586
     * @return void
587
     */
588
    public function clear()
589
    {
590
        $this->rules = [
591
            '*'       => [],
592
            'get'     => [],
593
            'post'    => [],
594
            'put'     => [],
595
            'patch'   => [],
596
            'delete'  => [],
597
            'head'    => [],
598
            'options' => [],
599
        ];
600
    }
601
}
602