From f38c6610fbb61b692c0ed61d2d5396feb7869828 Mon Sep 17 00:00:00 2001 From: kj Date: Wed, 18 May 2022 12:29:07 -0400 Subject: [PATCH] Allow multiple middlewares. --- src/Libs/Router.php | 21 ++++++++++----------- 1 file changed, 10 insertions(+), 11 deletions(-) diff --git a/src/Libs/Router.php b/src/Libs/Router.php index 98733aa..12b5a0c 100644 --- a/src/Libs/Router.php +++ b/src/Libs/Router.php @@ -21,7 +21,7 @@ class Router { private static $last; public static $notFoundCallback = 'Libs\Router::defaultNotFound'; - private static function defaultNotFound () { + public static function defaultNotFound () { header("HTTP/1.0 404 Not Found"); echo '

Error 404 - Página no encontrada

'; } @@ -58,7 +58,7 @@ class Router { return [ 'path' => $path, - 'callback' => $callback, + 'callback' => [$callback], 'paramNames' => $paramNames ]; } @@ -112,7 +112,7 @@ class Router { $callback = 'Middlewares\\'.$callback; } - static::$$method[$index]['middleware'] = $callback; + static::$$method[$index]['callback'][] = $callback; return new static(); } @@ -267,7 +267,7 @@ class Router { break; } - $args = static::getReq(); + $req = static::getReq(); foreach ($routers as $router) { // revisa todos los routers para ver si coinciden con la ruta actual if (preg_match_all('/^'.$router['path'].'\/?$/si',$path, $matches, PREG_PATTERN_ORDER)) { @@ -277,15 +277,14 @@ class Router { if (isset($matches[1])) { foreach ($matches as $index => $match) { $paramName = $router['paramNames'][$index-1]; - $args->params->$paramName = urldecode($match[0]); + $req->params->$paramName = urldecode($match[0]); } } - // Comprobando si hay middleware - if (isset($router['middleware'])) - $data = call_user_func_array($router['middleware'], [$router['callback'], $args]); - else - $data = call_user_func_array($router['callback'], [$args]); + // Llamar al último callback configurado + $next = array_pop($router['callback']); + $req->next = $router['callback']; + $data = call_user_func_array($next, [$req]); if (isset($data)) { header('Content-Type: application/json'); @@ -297,7 +296,7 @@ class Router { } // Si no hay router que coincida llamamos a $notFoundCallBack - call_user_func_array(static::$notFoundCallback, [$args]); + call_user_func_array(static::$notFoundCallback, [$req]); } } ?>