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