Completed
Push — 6.0 ( 723406...0734c3 )
by liu
03:21
created

RuleItem::setRule()   B

Complexity

Conditions 7
Paths 24

Size

Total Lines 23
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

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