Completed
Push — 6.0 ( 5e7dbe...93d811 )
by liu
16:07
created

RuleItem::setAutoOptions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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