Add validation on Request.

This commit is contained in:
KJ
2024-05-25 16:59:59 -04:00
parent cd1685d2e7
commit 59fff2a586
3 changed files with 287 additions and 46 deletions

View File

@ -290,29 +290,16 @@ class Router {
}
/**
* Aplica los routers.
* Aplica la configuración de rutas.
*
* Este método ha de ser llamado luego de que todos los routers hayan sido configurados.
* @param string $path (opcional) Ruta a usar. Si no se define, detecta la ruta actual.
*
* En caso que la ruta actual coincida con un router configurado, se comprueba si hay middleware; Si hay
* middleware, se enviará el callback y los datos de la petición como un Neuron. Caso contrario, se enviarán
* los datos directamente al callback.
*
* Con middleware:
* $middleware($callback, $req)
*
* Sin middleware:
* $callback($req)
*
* $req es una instancia de Neuron que tiene los datos de la petición.
*
* Si no la ruta no coincide con ninguna de las rutas configuradas, ejecutará el callback $notFoundCallback
* @return void
*/
public static function apply(): void
public static function apply(string $path = null): void
{
$path = static::currentPath();
$routers = match($_SERVER['REQUEST_METHOD']) { // Según el método selecciona un arreglo de routers configurados
$path = $path ?? static::currentPath();
$routers = match($_SERVER['REQUEST_METHOD']) { // Según el método selecciona un arreglo de routers
'POST' => static::$post,
'PUT' => static::$put,
'PATCH' => static::$patch,
@ -320,25 +307,58 @@ class Router {
default => static::$get
};
$req = new Request(static::currentPath());
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)) {
unset($matches[0]);
// Comprobando pseudo variables en la ruta
// Objtener un reflection del callback
$lastCallback = $router['callback'][0];
if ($lastCallback instanceof \Closure) { // si es función anónima
$reflectionCallback = new \ReflectionFunction($lastCallback);
} else {
if (is_string($lastCallback))
$lastCallback = preg_split('/::/', $lastCallback);
// Revisamos su es un método o solo una función
if (count($lastCallback) == 2)
$reflectionCallback = new \ReflectionMethod($lastCallback[0], $lastCallback[1]);
else
$reflectionCallback = new \ReflectionFunction($lastCallback[0]);
}
// Obtener los parámetros
$arguments = $reflectionCallback->getParameters();
if (isset($arguments[0])) {
// Obtenemos la clase del primer parámetro
$argumentClass = strval($arguments[0]->getType());
// Verificamos si la clase está o no tipada
if (empty($argumentClass)) {
$request = new Request;
} else {
$request = new $argumentClass;
// Verificamos que sea instancia de Request (requerimiento)
if (!($request instanceof Request))
throw new \Exception('Bad argument type on router callback.');
}
} else {
$request = new Request;
}
// Comprobando y guardando los parámetros variables de la ruta
if (isset($matches[1])) {
foreach ($matches as $index => $match) {
$paramName = $router['paramNames'][$index-1];
$req->params->$paramName = urldecode($match[0]);
$paramName = $router['paramNames'][$index-1];
$request->params->$paramName = urldecode($match[0]);
}
}
// Llamar al último callback configurado
$next = array_pop($router['callback']);
$req->next = $router['callback'];
$data = call_user_func_array($next, [$req]);
// Llama a la validación y luego procesa la cola de callbacks
$request->next = $router['callback'];
$data = $request->validate($request);
// Por defecto imprime como JSON si se retorna algo
if (isset($data)) {
header('Content-Type: application/json');
print(json_encode($data));
@ -349,7 +369,6 @@ class Router {
}
// Si no hay router que coincida llamamos a $notFoundCallBack
call_user_func_array(static::$notFoundCallback, [$req]);
call_user_func_array(static::$notFoundCallback, [new Request]);
}
}
?>