Passed
Push — master ( 6c61b1...eeeaaf )
by Zlatin
01:19
created

Route::compile()   B

Complexity

Conditions 5
Paths 6

Size

Total Lines 30
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 15.0936

Importance

Changes 0
Metric Value
cc 5
eloc 21
nc 6
nop 1
dl 0
loc 30
ccs 6
cts 23
cp 0.2609
crap 15.0936
rs 8.439
c 0
b 0
f 0
1
<?php
2
namespace DevOp\Core\Router;
3
4
class Route
5
{
6
7
    /**
8
     * @var string
9
     */
10
    private $pattern;
11
12
    /**
13
     * @var string
14
     */
15
    private $regEx;
16
17
    /**
18
     * @var array
19
     */
20
    private $parameters = [];
21
22
    /**
23
     * @var object|callback|array|string
24
     */
25
    private $callback;
26
27
    /**
28
     * @param string $name
29
     * @param string $pattern
30
     * @param object|callback|array|string $callback
31
     */
32 4
    public function __construct($pattern, $callback)
33
    {
34 4
        $this->pattern = $pattern;
35 4
        $this->callback = $callback;
36
        
37 4
        $this->compile($pattern);
38 4
    }
39
40
    /**
41
     * @return string
42
     */
43
    public function getRegEx()
44
    {
45
        return $this->regEx;
46
    }
47
48
    /**
49
     * @return string
50
     */
51
    public function getPattern()
52
    {
53
        return $this->pattern;
54
    }
55
56
    /**
57
     * @return array
58
     */
59
    public function getParameters()
60
    {
61
        return $this->getParameters();
62
    }
63
64
    /**
65
     * @return object|callback|array|string
66
     */
67
    public function getCallback()
68
    {
69
        return $this->callback;
70
    }
71
72 4
    public function compile($pattern)
73
    {
74 4
        $matches = [];
75 4
        preg_match_all('#\[(.*?)\]#s', $pattern, $matches, PREG_SET_ORDER);
76
77 4
        if (empty($matches)) {
78 4
            $this->regEx = "#^{$pattern}$#s";
79 4
            return;
80
        }
81
82
        $components = array_map(function($values) {
83
            return ['name' => $values[0], 'value' => $values[1]];
84
        }, $matches);
85
86
        $replaces = [];
87
        foreach ($components AS $route) {
88
            $placeholder = ltrim($route['value'], '/');
89
            $optional = substr($route['value'], 0, 1) === '/';
90
            if (strchr($placeholder, ':')) {
91
                list($parameter, $value) = explode(':', $placeholder);
92
                $regEx = "(?P<$parameter>{$value})";
93
                $this->parameters[] = $parameter;
94
            } else {
95
                $regEx = "(?P<$placeholder>[^/]++)";
96
                $this->parameters[] = $placeholder;
97
            }
98
            $replaces[$route['name']] = !$optional ? $regEx : "(?:/{$regEx})";
99
        }
100
101
        $this->regEx = sprintf("#^%s?$#s", str_replace(array_keys($replaces), array_values($replaces), $pattern));
102
    }
103
}
104