Allow multiple middlewares.

This commit is contained in:
kj 2022-05-18 12:29:07 -04:00
parent 4003a88f66
commit f38c6610fb
1 changed files with 10 additions and 11 deletions

View File

@ -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 '<h2 style="text-align: center;margin: 25px 0px;">Error 404 - Página no encontrada</h2>';
}
@ -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]);
}
}
?>