Completed
Push — 6.0 ( cb907d...4e9554 )
by liu
03:34
created

RuleItem::name()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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