added preference for static routes.

This commit is contained in:
tracer 2022-10-23 18:46:42 +02:00
parent 33618b3be0
commit 6284918056
1 changed files with 27 additions and 3 deletions

View File

@ -18,9 +18,15 @@ use Closure;
* Currently it doesn't handle GET requests, as not needed. * Currently it doesn't handle GET requests, as not needed.
* But if I reuse the code in my bind Api I'll enable GET as well. * But if I reuse the code in my bind Api I'll enable GET as well.
*/ */
class Router class Router
{ {
private array $routes; /*
* The easiest wy to differentiate between static and dynamic routes is using
* two arrays, no need to pollute the class Route with that information
*/
private array $staticRoutes;
private array $dynamicRoutes;
public function __construct(private readonly Template $template) public function __construct(private readonly Template $template)
{ {
@ -47,6 +53,12 @@ class Router
$regex = '/^' . str_replace(search: "/", replace: '\\/', subject: $regex) . '$/i'; $regex = '/^' . str_replace(search: "/", replace: '\\/', subject: $regex) . '$/i';
$route = new Route(name: $name, route: $route, regEx: $regex, parameters: $parameters, callback: $callback); $route = new Route(name: $name, route: $route, regEx: $regex, parameters: $parameters, callback: $callback);
if ($parameters) {
$this->dynamicRoutes[] = $route;
} else {
$this->staticRoutes[] = $route;
}
$this->routes[] = $route; $this->routes[] = $route;
} }
@ -57,7 +69,19 @@ class Router
{ {
$requestUri = $_SERVER['REQUEST_URI']; $requestUri = $_SERVER['REQUEST_URI'];
foreach ($this->routes as $route) { /*
* Static routes have preference over dynamic ones, so
* /admin/user/add to add and
* /admin/user/{name} to edit is possible.
*/
foreach ($this->staticRoutes as $route) {
if (preg_match(pattern: $route->getRegex(), subject: $requestUri, matches: $matches)) {
call_user_func(callback: $route->getCallback());
return;
}
}
foreach ($this->dynamicRoutes as $route) {
if (preg_match(pattern: $route->getRegex(), subject: $requestUri, matches: $matches)) { if (preg_match(pattern: $route->getRegex(), subject: $requestUri, matches: $matches)) {
$parameters = []; $parameters = [];
foreach ($route->getParameters() as $id => $parameter) { foreach ($route->getParameters() as $id => $parameter) {