Test Failed
Branch master (fb3e9d)
by 世昌
03:53
created

MatchBuilder   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 26
dl 0
loc 40
rs 10
c 0
b 0
f 0
wmc 4

1 Method

Rating   Name   Duplication   Size   Complexity  
A build() 0 31 4
1
<?php
2
namespace nebula\route\uri;
3
4
use Exception;
5
use nebula\route\uri\UriMatcher;
6
use nebula\route\uri\parameter\IntParameter;
7
use nebula\route\uri\parameter\UrlParameter;
8
use nebula\route\uri\parameter\FloatParameter;
9
use nebula\route\uri\parameter\StringParameter;
10
11
/**
12
 * 可执行命令表达式
13
 *
14
 */
15
class MatchBuilder
16
{
17
    protected static $parameters = [
18
        'float' => FloatParameter::class,
19
        'int' => IntParameter::class,
20
        'string' => StringParameter::class,
21
        'url' => UrlParameter::class,
22
    ];
23
24
    public static function build(string $uri):UriMatcher
25
    {
26
        // 参数
27
        $parameters = [];
28
        // 转义正则
29
        $url=preg_replace('/([\/\.\\\\\+\(\^\)\$\!\<\>\-\?\*])/', '\\\\$1', $uri);
30
        // 添加忽略
31
        $url=preg_replace('/(\[)([^\[\]]+)(?(1)\])/', '(?:$2)?', $url);
32
        // 添加 * ? 匹配
33
        $url=str_replace(['\*','\?'],['[^/]+?','[^/]'], $url);
34
        // 编译页面参数
35
        $url=preg_replace_callback('/\{(\w+)(?:\:([^}]+?))?\}/', function ($match) use (&$parameters) {
36
            $name = $match[1];
37
            $type = 'string';
38
            $extra = '';
39
            if (isset($match[2])) {
40
                if (strpos($match[2], '=')!==false) {
41
                    list($type, $extra) = \explode('=', $match[2]);
42
                } else {
43
                    $type = $match[2];
44
                }
45
            }
46
            if (!\in_array($type, array_keys(MatchBuilder::$parameters))) {
47
                throw new Exception(sprintf('unknown parameter type %s', $type), 1);
48
            }
49
            $parameter = MatchBuilder::$parameters[$type]::build($name, $extra);
50
            $parameters[] = $parameter;
51
            return $parameter->getMatch();
52
        }, $url);
53
54
        return new UriMatcher($url, $parameters);
55
    }
56
}
57