Passed
Push — 8.0 ( efb207...1ced43 )
by liu
02:33
created

RuleItem   C

Complexity

Total Complexity 56

Size/Duplication

Total Lines 297
Duplicated Lines 0 %

Test Coverage

Coverage 58%

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 95
dl 0
loc 297
ccs 58
cts 100
cp 0.58
rs 5.5199
c 3
b 0
f 0
wmc 56

12 Methods

Rating   Name   Duplication   Size   Complexity  
A setMiss() 0 4 1
A isMiss() 0 3 1
B setRule() 0 23 7
A setRuleName() 0 4 2
A name() 0 6 1
A check() 0 3 1
A getSuffix() 0 11 3
A __construct() 0 11 1
A urlSuffixCheck() 0 14 4
A checkRule() 0 21 4
A group() 0 10 2
D checkMatch() 0 67 29

How to fix   Complexity   

Complex Class

Complex classes like RuleItem often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use RuleItem, and based on these observations, apply Extract Interface, too.

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 think\Exception;
16
use think\facade\Validate;
17
use think\Request;
18
use think\Route;
19
20
/**
21
 * 路由规则类
22
 */
23
class RuleItem extends Rule
24
{
25
    /**
26
     * 是否为MISS规则
27
     * @var bool
28
     */
29
    protected $miss = false;
30
31
    /**
32
     * 是否为额外自动注册的OPTIONS规则
33
     * @var bool
34
     */
35
    protected $autoOption = false;
36
37
    /**
38
     * 架构函数
39
     * @access public
40
     * @param  Route             $router 路由实例
41
     * @param  RuleGroup         $parent 上级对象
42
     * @param  string            $name 路由标识
43
     * @param  string            $rule 路由规则
44
     * @param  string|\Closure   $route 路由地址
45
     * @param  string            $method 请求类型
46
     */
47 27
    public function __construct(Route $router, RuleGroup $parent, ?string $name = null, string $rule = '', $route = null, string $method = '*')
48
    {
49 27
        $this->router = $router;
50 27
        $this->parent = $parent;
51 27
        $this->name   = $name;
52 27
        $this->route  = $route;
53 27
        $this->method = $method;
54
55 27
        $this->setRule($rule);
56
57 27
        $this->router->setRule($this->rule, $this);
58
    }
59
60
    /**
61
     * 设置当前路由规则为MISS路由
62
     * @access public
63
     * @return $this
64
     */
65 27
    public function setMiss()
66
    {
67 27
        $this->miss = true;
68 27
        return $this;
69
    }
70
71
    /**
72
     * 判断当前路由规则是否为MISS路由
73
     * @access public
74
     * @return bool
75
     */
76
    public function isMiss(): bool
77
    {
78
        return $this->miss;
79
    }
80
81
    /**
82
     * 获取当前路由的URL后缀
83
     * @access public
84
     * @return string|null
85
     */
86 9
    public function getSuffix(): ?string
87
    {
88 9
        if (isset($this->option['ext'])) {
89
            $suffix = $this->option['ext'];
90 9
        } elseif ($this->parent->getOption('ext')) {
91
            $suffix = $this->parent->getOption('ext');
92
        } else {
93 9
            $suffix = null;
94
        }
95
96 9
        return $suffix;
97
    }
98
99
    /**
100
     * 路由规则预处理
101
     * @access public
102
     * @param  string      $rule     路由规则
103
     * @return void
104
     */
105 27
    public function setRule(string $rule): void
106
    {
107 27
        if (str_ends_with($rule, '$')) {
108
            // 是否完整匹配
109 3
            $rule = substr($rule, 0, -1);
110
111 3
            $this->option['complete_match'] = true;
112
        }
113
114 27
        $rule = '/' != $rule ? ltrim($rule, '/') : '';
115
116 27
        if ($this->parent && $prefix = $this->parent->getFullName()) {
117
            $rule = $prefix . ($rule ? '/' . ltrim($rule, '/') : '');
118
        }
119
120 27
        if (str_contains($rule, ':')) {
121
            $this->rule = preg_replace(['/\[\:(\w+)\]/', '/\:(\w+)/'], ['<\1?>', '<\1>'], $rule);
122
        } else {
123 27
            $this->rule = $rule;
124
        }
125
126
        // 生成路由标识的快捷访问
127 27
        $this->setRuleName();
128
    }
129
130
    /**
131
     * 设置别名
132
     * @access public
133
     * @param  string     $name
134
     * @return $this
135
     */
136
    public function name(string $name)
137
    {
138
        $this->name = $name;
139
        $this->setRuleName(true);
140
141
        return $this;
142
    }
143
144
    /**
145
     * 设置路由标识 用于URL反解生成
146
     * @access protected
147
     * @param  bool $first 是否插入开头
148
     * @return void
149
     */
150 27
    protected function setRuleName(bool $first = false): void
151
    {
152 27
        if ($this->name) {
153 9
            $this->router->setName($this->name, $this, $first);
154
        }
155
    }
156
157
    /**
158
     * 检测路由
159
     * @access public
160
     * @param  Request      $request  请求对象
161
     * @param  string       $url      访问地址
162
     * @param  array        $match    匹配路由变量
163
     * @param  bool         $completeMatch   路由是否完全匹配
164
     * @return Dispatch|false
165
     */
166 24
    public function checkRule(Request $request, string $url, ?array $match = null, bool $completeMatch = false)
167
    {
168
        // 检查参数有效性
169 24
        if (!$this->checkOption($this->option, $request)) {
170
            return false;
171
        }
172
173
        // 合并分组参数
174 24
        $option  = $this->getOption();
175 24
        $pattern = $this->getPattern();
176 24
        $url     = $this->urlSuffixCheck($request, $url, $option);
177
178 24
        if (is_null($match)) {
179 24
            $match = $this->checkMatch($url, $option, $pattern, $completeMatch);
180
        }
181
182 24
        if (false !== $match) {
183 24
            return $this->parseRule($request, $this->rule, $this->route, $url, $option, $match);
184
        }
185
186
        return false;
187
    }
188
189
    /**
190
     * 检测路由(含路由匹配)
191
     * @access public
192
     * @param  Request      $request  请求对象
193
     * @param  string       $url      访问地址
194
     * @param  bool         $completeMatch   路由是否完全匹配
195
     * @return Dispatch|false
196
     */
197 24
    public function check(Request $request, string $url, bool $completeMatch = false)
198
    {
199 24
        return $this->checkRule($request, $url, null, $completeMatch);
200
    }
201
202
    /**
203
     * URL后缀及Slash检查
204
     * @access protected
205
     * @param  Request      $request  请求对象
206
     * @param  string       $url      访问地址
207
     * @param  array        $option   路由参数
208
     * @return string
209
     */
210 24
    protected function urlSuffixCheck(Request $request, string $url, array $option = []): string
211
    {
212
        // 是否区分 / 地址访问
213 24
        if (!empty($option['remove_slash']) && '/' != $this->rule) {
214
            $this->rule = rtrim($this->rule, '/');
215
            $url        = rtrim($url, '|');
216
        }
217
218 24
        if (isset($option['ext'])) {
219
            // 路由ext参数 优先于系统配置的URL伪静态后缀参数
220
            $url = preg_replace('/\.(' . $request->ext() . ')$/i', '', $url);
221
        }
222
223 24
        return $url;
224
    }
225
226
    /**
227
     * 检测URL和规则路由是否匹配
228
     * @access private
229
     * @param  string    $url URL地址
230
     * @param  array     $option    路由参数
231
     * @param  array     $pattern   变量规则
232
     * @param  bool      $completeMatch   是否完全匹配
233
     * @return array|false
234
     */
235 24
    private function checkMatch(string $url, array $option, array $pattern, bool $completeMatch)
236
    {
237 24
        if (isset($option['complete_match'])) {
238 3
            $completeMatch = $option['complete_match'];
239
        }
240
241 24
        $depr = $this->config('pathinfo_depr');
242 24
        if (isset($option['case_sensitive'])) {
243
            $case = $option['case_sensitive'];
244
        } else {
245 24
            $case = $this->config('url_case_sensitive');
246
        }
247
248
        // 检查完整规则定义
249 24
        if (isset($pattern['__url__']) && !preg_match(str_starts_with($pattern['__url__'], '/') ? $pattern['__url__'] : '/^' . $pattern['__url__'] . ($completeMatch ? '$' : '') . '/', str_replace('|', $depr, $url))) {
250
            return false;
251
        }
252
253 24
        $var  = [];
254 24
        $url  = $depr . str_replace('|', $depr, $url);
255 24
        $rule = $depr . str_replace('/', $depr, $this->rule);
256
257 24
        if ($depr == $rule && $depr != $url) {
258
            return false;
259
        }
260
261 24
        if (!str_contains($rule, '<')) {
262 24
            if ($case && (0 === strcmp($rule, $url) || (!$completeMatch && 0 === strncmp($rule . $depr, $url . $depr, strlen($rule . $depr))))) {
263
                return $var;
264 24
            } elseif (!$case && (0 === strcasecmp($rule, $url) || (!$completeMatch && 0 === strncasecmp($rule . $depr, $url . $depr, strlen($rule . $depr))))) {
265 24
                return $var;
266
            }
267
            return false;
268
        }
269
270
        $slash = preg_quote('/-' . $depr, '/');
271
272
        if ($matchRule = preg_split('/[' . $slash . ']?<\w+\??>/', $rule, 2)) {
273
            if ($matchRule[0] && 0 !== strncasecmp($rule, $url, strlen($matchRule[0]))) {
274
                return false;
275
            }
276
        }
277
278
        if (preg_match_all('/[' . $slash . ']?<?\w+\??>?/', $rule, $matches)) {
279
            $regex = $this->buildRuleRegex($rule, $matches[0], $pattern, $option, $completeMatch);
280
281
            try {
282
                if (!preg_match('~^' . $regex . '~u' . ($case ? '' : 'i'), $url, $match)) {
283
                    return false;
284
                }
285
            } catch (\Exception $e) {
286
                throw new Exception('route pattern error');
287
            }
288
289
            foreach ($match as $key => $val) {
290
                if (is_string($key)) {
291
                    $var[$key] = $val;
292
                    if (isset($option['var_rule'][$key]) && !Validate::checkRule($val, $option['var_rule'][$key])) {
293
                        // 检查变量
294
                        return false;
295
                    }
296
                }
297
            }
298
        }
299
300
        // 成功匹配后返回URL中的动态变量数组
301
        return $var;
302
    }
303
304
    /**
305
     * 设置路由所属分组(用于注解路由)
306
     * @access public
307
     * @param  string $name 分组名称或者标识
308
     * @return $this
309
     */
310
    public function group(string $name)
311
    {
312
        $group = $this->router->getRuleName()->getGroup($name);
313
314
        if ($group) {
315
            $this->parent = $group;
316
            $this->setRule($this->rule);
317
        }
318
319
        return $this;
320
    }
321
}
322