55class Router
66{
77 private static array $ routes = [];
8- private static array $ constraints = [];
98 private static $ pathNotFound ;
109 private static $ methodNotAllowed ;
1110 private static string $ defaultConstraint = '([\w\-]+) ' ;
1211 private static string $ currentPrefix = '' ;
12+ private static string $ lastInsertedRoute = '' ;
1313
1414 /**
1515 * A quick static function to register a route in the router. Used by the shorthand methods as well.
@@ -26,12 +26,17 @@ public static function add(string $route, callable|string $action, string|array
2626 $ route = self ::$ currentPrefix .$ route ;
2727 }
2828
29- self ::$ routes [] = [
30- 'route ' => self ::trimRoute ($ route ),
29+ $ trimmed = self ::trimRoute ($ route );
30+
31+ self ::$ routes [$ trimmed ] = [
32+ 'route ' => $ trimmed ,
3133 'action ' => $ action ,
32- 'methods ' => $ methods
34+ 'methods ' => $ methods ,
35+ 'constraints ' => []
3336 ];
3437
38+ self ::$ lastInsertedRoute = $ trimmed ;
39+
3540 return new self ;
3641 }
3742
@@ -136,15 +141,17 @@ public static function prefix(string $prefix, callable $routes)
136141 */
137142 public static function with (string |array $ parameter , string $ constraint = '' )
138143 {
144+ $ last = self ::$ lastInsertedRoute ;
145+
139146 if (is_array ($ parameter )) {
140147 foreach ($ parameter as $ param => $ constraint ) {
141- self ::$ constraints [$ param ] = $ constraint ;
148+ self ::$ routes [ $ last ][ ' constraints ' ] [$ param ] = $ constraint ;
142149 }
143150
144151 return new self ;
145152 }
146153
147- self ::$ constraints [$ parameter ] = $ constraint ;
154+ self ::$ routes [ $ last ][ ' constraints ' ] [$ parameter ] = $ constraint ;
148155
149156 return new self ;
150157 }
@@ -157,17 +164,18 @@ public static function with(string|array $parameter, string $constraint = '')
157164 */
158165 private static function tokenize (string $ uri )
159166 {
160- $ constraints = array_keys (self ::$ constraints );
167+ $ constraints = self ::$ routes [$ uri ]['constraints ' ];
168+ $ constraintKeys = array_keys ($ constraints );
161169
162170 preg_match_all ('/(?:{([\w\-]+)})+/ ' , $ uri , $ matches );
163171 $ matches = $ matches [1 ];
164172
165173 foreach ($ matches as $ match ) {
166174 $ pattern = '{ ' .$ match .'} ' ;
167175
168- if (in_array ($ match , $ constraints )) {
176+ if (in_array ($ match , $ constraintKeys )) {
169177 // Do some voodoo to allow users to use parentheses in their constraints if they want
170- $ constraint = '( ' .rtrim (ltrim (trim (self :: $ constraints [$ match ]), '( ' ), ') ' ).') ' ;
178+ $ constraint = '( ' .rtrim (ltrim (trim ($ constraints [$ match ]), '( ' ), ') ' ).') ' ;
171179
172180 $ uri = str_replace ($ pattern , $ constraint , $ uri );
173181 } else {
0 commit comments