-
Notifications
You must be signed in to change notification settings - Fork 0
/
route_test.php
97 lines (62 loc) · 2.05 KB
/
route_test.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
<?php
class Route {
protected $pattern;
protected $defaults;
protected $req;
protected $regex;
protected $capture_indexes;
public function __construct($pattern, $opts = array()) {
foreach(array('requirements', 'defaults') as $opt)
$this->$opt = isset($opts[$opt]) ? $opts[$opt] : array();
# move the format from the pattern into requirements
if(preg_match('/^(.+)\.(\w+)$/', $pattern, $matches)) {
$pattern = $matches[1];
$this->requirements['format'] = $matches[2];
}
$this->pattern = trim($pattern, '/');
$this->compile();
}
public function matches_request($request) {
# match method
# match format
# match pattern
# controller exists
}
private function compile() {
$match_index = 0;
$regex = array();
foreach(explode('/', $this->pattern) as $segment) {
# empty routes (root) dont contain any slashes
if($segment == '')
continue;
# static route segment, this value is fixed and does not get captured
if($segment[0] != ':') {
$regex[] = $segment;
$match_index += $this->count_captures($segment);
continue;
}
# if we got this far there is a named segment (starts with a colon)
# that needs to be captured
# prune the leading : from the segment
$segment = substr($segment, 1);
# keep track of which regex-match-offset this segment will be
$this->capture_indexes[++$match_index] = $segment;
if(isset($this->requirements[$segment])) {
$req = preg_replace('/\./', '[^/]', $this->requirements[$segment]);
$match_index += $this->count_captures($req);
$regex[] = "($req)";
} else if($segment == 'controller') {
$regex[] = '(\w[/\w]*)';
} else if($segment == 'action') {
$regex[] = '(\w+)';
} else {
$regex[] = '([^/]+)';
}
}
$regex = impolode('/', $regex);
$this->regex = "#^$regex$#";
}
private function count_captures() {
return preg_match_all('/\(/', $str, $discard);
}
}