Passed
Push — 8.0 ( 06cb92...10ab89 )
by liu
10:19
created

RuleGroup::getDomain()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
// +----------------------------------------------------------------------
3
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
4
// +----------------------------------------------------------------------
5
// | Copyright (c) 2006~2023 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\Route;
20
21
/**
22
 * 路由分组类
23
 */
24
class RuleGroup extends Rule
25
{
26
    /**
27
     * 分组路由(包括子分组)
28
     * @var Rule[]
29
     */
30
    protected $rules = [];
31
32
    /**
33
     * MISS路由
34
     * @var RuleItem
35
     */
36
    protected $miss;
37
38
    /**
39
     * 完整名称
40
     * @var string
41
     */
42
    protected $fullName;
43
44
    /**
45
     * 分组别名
46
     * @var string
47
     */
48
    protected $alias;
49
50
    /**
51
     * 是否已经解析
52
     * @var bool
53
     */
54
    protected $hasParsed;
55
56
    /**
57
     * 架构函数
58
     * @access public
59
     * @param  Route     $router 路由对象
60
     * @param  RuleGroup $parent 上级对象
61
     * @param  string    $name   分组名称
62
     * @param  mixed     $rule   分组路由
63
     * @param  bool      $lazy   延迟解析
64
     */
65 3
    public function __construct(Route $router, RuleGroup $parent = null, string $name = '', $rule = null, bool $lazy = false)
66
    {
67 3
        $this->router = $router;
68 3
        $this->parent = $parent;
69 3
        $this->rule   = $rule;
70 3
        $this->name   = trim($name, '/');
71
72 3
        $this->setFullName();
73
74 3
        if ($this->parent) {
75 3
            $this->domain = $this->parent->getDomain();
76 3
            $this->parent->addRuleItem($this);
77
        }
78
79 3
        if (!$lazy) {
80 3
            $this->parseGroupRule($rule);
81
        }
82
    }
83
84
    /**
85
     * 设置分组的路由规则
86
     * @access public
87
     * @return void
88
     */
89 3
    protected function setFullName(): void
90
    {
91 3
        if (str_contains($this->name, ':')) {
92
            $this->name = preg_replace(['/\[\:(\w+)\]/', '/\:(\w+)/'], ['<\1?>', '<\1>'], $this->name);
93
        }
94
95 3
        if ($this->parent && $this->parent->getFullName()) {
96
            $this->fullName = $this->parent->getFullName() . ($this->name ? '/' . $this->name : '');
97
        } else {
98 3
            $this->fullName = $this->name;
99
        }
100
101 3
        if ($this->name) {
102
            $this->router->getRuleName()->setGroup($this->name, $this);
103
        }
104
    }
105
106
    /**
107
     * 获取所属域名
108
     * @access public
109
     * @return string
110
     */
111 12
    public function getDomain(): string
112
    {
113 12
        return $this->domain ?: '-';
114
    }
115
116
    /**
117
     * 获取分组别名
118
     * @access public
119
     * @return string
120
     */
121
    public function getAlias(): string
122
    {
123
        return $this->alias ?: '';
124
    }
125
126
    /**
127
     * 检测分组路由
128
     * @access public
129
     * @param  Request $request       请求对象
130
     * @param  string  $url           访问地址
131
     * @param  bool    $completeMatch 路由是否完全匹配
132
     * @return Dispatch|false
133
     */
134 27
    public function check(Request $request, string $url, bool $completeMatch = false)
135
    {
136
        // 检查分组有效性
137 27
        if (!$this->checkOption($this->option, $request) || !$this->checkUrl($url)) {
138
            return false;
139
        }
140
141
        // 解析分组路由
142 27
        if (!$this->hasParsed) {
143 24
            $this->parseGroupRule($this->rule);
144
        }
145
146
        // 获取当前路由规则
147 27
        $method = strtolower($request->method());
148 27
        $rules  = $this->getRules($method);
149 27
        $option = $this->getOption();
150
151 27
        if (isset($option['complete_match'])) {
152
            $completeMatch = $option['complete_match'];
153
        }
154
155 27
        if (!empty($option['merge_rule_regex'])) {
156
            // 合并路由正则规则进行路由匹配检查
157
            $result = $this->checkMergeRuleRegex($request, $rules, $url, $completeMatch);
158
159
            if (false !== $result) {
160
                return $result;
161
            }
162
        }
163
164
        // 检查分组路由
165 27
        foreach ($rules as $item) {
166 24
            $result = $item->check($request, $url, $completeMatch);
167
168 24
            if (false !== $result) {
169 24
                return $result;
170
            }
171
        }
172
173 6
        if (!empty($option['dispatcher'])) {
174
            $result = $this->parseRule($request, '', $option['dispatcher'], $url, $option);
175 6
        } elseif ($miss = $this->getMissRule($method)) {
176
            // 未匹配所有路由的路由规则处理
177 3
            $result = $miss->parseRule($request, '', $miss->getRoute(), $url, $miss->getOption());
178
        } else {
179 3
            $result = false;
180
        }
181
182 6
        return $result;
183
    }
184
185
    /**
186
     * 分组URL匹配检查
187
     * @access protected
188
     * @param  string $url URL
189
     * @return bool
190
     */
191 27
    protected function checkUrl(string $url): bool
192
    {
193 27
        if ($this->fullName) {
194
            $pos = strpos($this->fullName, '<');
195
196
            if (false !== $pos) {
197
                $str = substr($this->fullName, 0, $pos);
198
            } else {
199
                $str = $this->fullName;
200
            }
201
202
            if ($str && 0 !== stripos(str_replace('|', '/', $url), $str)) {
203
                return false;
204
            }
205
        }
206
207 27
        return true;
208
    }
209
210
    /**
211
     * 设置路由分组别名
212
     * @access public
213
     * @param  string $alias 路由分组别名
214
     * @return $this
215
     */
216
    public function alias(string $alias)
217
    {
218
        $this->alias = $alias;
219
        $this->router->getRuleName()->setGroup($alias, $this);
220
221
        return $this;
222
    }
223
224
    /**
225
     * 解析分组和域名的路由规则及绑定
226
     * @access public
227
     * @param  mixed $rule 路由规则
228
     * @return void
229
     */
230 27
    public function parseGroupRule($rule): void
231
    {
232 27
        if (is_string($rule) && is_subclass_of($rule, Dispatch::class)) {
233
            $this->dispatcher($rule);
234
            return;
235
        }
236
237 27
        $origin = $this->router->getGroup();
238 27
        $this->router->setGroup($this);
239
240 27
        if ($rule instanceof Closure) {
241 6
            Container::getInstance()->invokeFunction($rule);
242 24
        } elseif (is_string($rule) && $rule) {
243
            $this->router->bind($rule, $this->domain);
244
        }
245
246 27
        $this->router->setGroup($origin);
247 27
        $this->hasParsed = true;
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->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 (!str_contains($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
                    [$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 (str_starts_with(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
     * @param  string|Closure $route  路由地址
355
     * @param  string         $method 请求类型
356
     * @return RuleItem
357
     */
358 27
    public function miss(string|Closure $route, string $method = '*'): RuleItem
359
    {
360
        // 创建路由规则实例
361 27
        $method     =   strtolower($method);
362 27
        $ruleItem   =   new RuleItem($this->router, $this, null, '', $route, $method);
363
364 27
        $this->miss[$method] = $ruleItem->setMiss();
365
366 27
        return $ruleItem;
367
    }
368
369
    /**
370
     * 添加分组下的MISS路由
371
     * @access public
372
     * @param  string $method 请求类型
373
     * @return RuleItem|null
374
     */
375 6
    public function getMissRule(string $method = '*'): ?RuleItem
376
    {
377 6
        if (isset($this->miss[$method])) {
378 3
            $miss = $this->miss[$method];
379 3
        } elseif (isset($this->miss['*'])) {
380
            $miss = $this->miss['*'];
381
        } else {
382 3
            return null;
383
        }
384 3
        return $miss;
385
    }
386
387
    /**
388
     * 添加分组下的路由规则
389
     * @access public
390
     * @param  string $rule   路由规则
391
     * @param  mixed  $route  路由地址
392
     * @param  string $method 请求类型
393
     * @return RuleItem
394
     */
395 24
    public function addRule(string $rule, $route = null, string $method = '*'): RuleItem
396
    {
397
        // 读取路由标识
398 24
        if (is_string($route)) {
399 9
            $name = $route;
400
        } else {
401 15
            $name = null;
402
        }
403
404 24
        $method = strtolower($method);
405
406 24
        if ('' === $rule || '/' === $rule) {
407 3
            $rule .= '$';
408
        }
409
410
        // 创建路由规则实例
411 24
        $ruleItem = new RuleItem($this->router, $this, $name, $rule, $route, $method);
412
413 24
        $this->addRuleItem($ruleItem);
414
415 24
        return $ruleItem;
416
    }
417
418
    /**
419
     * 注册分组下的路由规则
420
     * @access public
421
     * @param  Rule   $rule   路由规则
422
     * @return $this
423
     */
424 24
    public function addRuleItem(Rule $rule)
425
    {
426 24
        $this->rules[] = $rule;
427 24
        return $this;
428
    }
429
430
    /**
431
     * 设置分组的路由前缀
432
     * @access public
433
     * @param  string $prefix 路由前缀
434
     * @return $this
435
     */
436
    public function prefix(string $prefix)
437
    {
438
        if ($this->parent && $this->parent->getOption('prefix')) {
439
            $prefix = $this->parent->getOption('prefix') . $prefix;
440
        }
441
442
        return $this->setOption('prefix', $prefix);
443
    }
444
445
    /**
446
     * 合并分组的路由规则正则
447
     * @access public
448
     * @param  bool $merge 是否合并
449
     * @return $this
450
     */
451 6
    public function mergeRuleRegex(bool $merge = true)
452
    {
453 6
        return $this->setOption('merge_rule_regex', $merge);
454
    }
455
456
    /**
457
     * 设置分组的Dispatch调度
458
     * @access public
459
     * @param  string $dispatch 调度类
460
     * @return $this
461
     */
462
    public function dispatcher(string $dispatch)
463
    {
464
        return $this->setOption('dispatcher', $dispatch);
465
    }
466
467
    /**
468
     * 获取完整分组Name
469
     * @access public
470
     * @return string
471
     */
472 27
    public function getFullName(): string
473
    {
474 27
        return $this->fullName ?: '';
475
    }
476
477
    /**
478
     * 获取分组的路由规则
479
     * @access public
480
     * @param  string $method 请求类型
481
     * @return array
482
     */
483 27
    public function getRules(string $method = ''): array
484
    {
485 27
        if ('' === $method) {
486
            return $this->rules;
487
        }
488
489 27
        return array_filter($this->rules, function ($item) use ($method) {
490 24
            $ruleMethod = $item->getMethod();
491 24
            return '*' == $ruleMethod || str_contains($ruleMethod, $method);
492 27
        });
493
    }
494
495
    /**
496
     * 清空分组下的路由规则
497
     * @access public
498
     * @return void
499
     */
500
    public function clear(): void
501
    {
502
        $this->rules = [];
503
    }
504
}
505