Passed
Push — 6.0 ( 45da49...66e043 )
by liu
02:23
created

RuleGroup::parseGroupRule()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

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