Passed
Push — 5.2 ( 0bda5c...c9419d )
by liu
02:51
created

RuleGroup::__construct()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

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