1
1
<?php
2
2
namespace TastRouter ;
3
3
4
-
5
4
/**
6
5
* Class Router
7
6
* @package TastRouter
8
- * @author xujiajun
7
+ * @author xujiajun [github.com/xujiajun]
9
8
*/
10
9
class Router
11
10
{
@@ -28,6 +27,19 @@ public function __construct(RouteCollection $routeCollection)
28
27
$ this ->routes = $ routeCollection ;
29
28
}
30
29
30
+ /**
31
+ * @return array|RouteCollection
32
+ */
33
+ public function getRoutes ()
34
+ {
35
+ return $ this ->routes ;
36
+ }
37
+
38
+ public function setRoutes (RouteCollection $ routes )
39
+ {
40
+ $ this ->routes = $ routes ;
41
+ }
42
+
31
43
/**
32
44
* @return mixed
33
45
*/
@@ -44,6 +56,7 @@ public function matchCurrentRequest()
44
56
if (($ pos = strpos ($ requestUrl , '? ' )) !== false ) {
45
57
$ requestUrl = substr ($ requestUrl , 0 , $ pos );
46
58
}
59
+
47
60
return $ this ->match ($ requestUrl , $ requestMethod );
48
61
}
49
62
@@ -57,6 +70,8 @@ public function match($requestUrl, $requestMethod = 'GET')
57
70
{
58
71
$ isRegexp = false ;
59
72
73
+ $ this ->_bind ();
74
+
60
75
foreach ($ this ->routes ->all () as $ route ) {
61
76
62
77
if (strpos ($ requestUrl , $ route ->getNamekey (), 0 )) {
@@ -68,11 +83,6 @@ public function match($requestUrl, $requestMethod = 'GET')
68
83
}
69
84
70
85
$ url = $ route ->getUrl ();
71
- //bind name
72
- $ name = $ route ->getName ();
73
- if (!empty ($ name )) {
74
- $ this ->namedroute [$ name ] = $ route ;
75
- }
76
86
77
87
if (in_array ($ requestUrl , (array )$ url )) {
78
88
$ route ->dispatch ();
@@ -88,7 +98,6 @@ public function match($requestUrl, $requestMethod = 'GET')
88
98
$ route ->dispatch ();
89
99
return $ route ;
90
100
}
91
-
92
101
return null ;
93
102
}
94
103
@@ -107,14 +116,12 @@ public function generate($routeName, array $parameters = [])
107
116
$ url = $ this ->namedroute [$ routeName ]->getUrl ();
108
117
preg_match_all ('/\/{\w+}\/?/ ' , $ url , $ matches );
109
118
$ matches = $ matches [0 ];
110
-
111
119
if (!empty ($ matches )) {
112
120
$ matches [count ($ matches ) - 1 ] .= '/ ' ;
113
121
return preg_replace ($ matches , array_reverse ($ parameters ), $ url );
114
122
}
115
123
116
124
return $ url ;
117
-
118
125
}
119
126
120
127
/**
@@ -142,6 +149,17 @@ public static function parseConfig(array $config)
142
149
return new Router ($ collection );
143
150
}
144
151
152
+ //bind name
153
+ private function _bind ()
154
+ {
155
+ foreach ($ this ->routes ->all () as $ route ) {
156
+ $ name = $ route ->getName ();
157
+ if (!empty ($ name )) {
158
+ $ this ->namedroute [$ name ] = $ route ;
159
+ }
160
+ }
161
+ }
162
+
145
163
/**
146
164
* @param $url
147
165
* @param $requestUrl
0 commit comments