docs: Improve documentation and translate comments to English
This commit is contained in:
@@ -5,13 +5,13 @@ namespace Libs;
|
||||
/**
|
||||
* Router - DuckBrain
|
||||
*
|
||||
* Librería de Enrrutador.
|
||||
* Depende de manera forzada de que la constante ROOT_DIR esté definida
|
||||
* y de manera optativa de que la constante SITE_URL lo esté también.
|
||||
* Router library.
|
||||
* It strictly depends on the ROOT_DIR constant being defined
|
||||
* and optionally on the SITE_URL constant being defined.
|
||||
*
|
||||
* @author KJ
|
||||
* @website https://kj2.me
|
||||
* @licence MIT
|
||||
* @license MIT
|
||||
*/
|
||||
class Router
|
||||
{
|
||||
@@ -20,20 +20,36 @@ class Router
|
||||
private static $put = [];
|
||||
private static $patch = [];
|
||||
private static $delete = [];
|
||||
/**
|
||||
* Stores the method and index of the last configured route, e.g., ['get', 0].
|
||||
* Used for chaining methods like middleware() or reconfigure().
|
||||
*
|
||||
* @var array|null
|
||||
*/
|
||||
private static $last;
|
||||
/**
|
||||
* Stores the parameters extracted from the current matching route.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $currentParams = [];
|
||||
/**
|
||||
* The callback function to be executed when no route matches.
|
||||
*
|
||||
* @var callable|string
|
||||
*/
|
||||
public static $notFoundCallback = 'Libs\Router::defaultNotFound';
|
||||
|
||||
/**
|
||||
* Función callback por defectio para cuando
|
||||
* no se encuentra configurada la ruta.
|
||||
* Default callback function for when
|
||||
* the route is not found.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function defaultNotFound(): void
|
||||
{
|
||||
header("HTTP/1.0 404 Not Found");
|
||||
echo '<h2 style="text-align: center;margin: 25px 0px;">Error 404 - Página no encontrada</h2>';
|
||||
echo '<h2 style="text-align: center;margin: 25px 0px;">Error 404 - Page Not Found</h2>';
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -44,18 +60,19 @@ class Router
|
||||
}
|
||||
|
||||
/**
|
||||
* Parsea para deectar las pseudovariables (ej: {variable})
|
||||
* Parses to detect pseudovariables (e.g., {variable})
|
||||
*
|
||||
* @param string $path
|
||||
* Ruta con pseudovariables.
|
||||
* Route with pseudovariables.
|
||||
*
|
||||
* @param callable $callback
|
||||
* Callback que será llamado cuando la ruta configurada en $path coincida.
|
||||
* Callback that will be called when the route configured in $path matches.
|
||||
*
|
||||
* @return array
|
||||
* Arreglo con 2 índices:
|
||||
* path - Contiene la ruta con las pseudovariables reeplazadas por expresiones regulares.
|
||||
* callback - Contiene el callback en formato Namespace\Clase::Método.
|
||||
* Array with 3 indices:
|
||||
* path - Contains the route with pseudovariables replaced by regular expressions.
|
||||
* callback - Contains the callback in Namespace\Class::Method format.
|
||||
* paramNames - An array of parameter names found in the path.
|
||||
*/
|
||||
private static function parse(string $path, callable $callback): array
|
||||
{
|
||||
@@ -78,10 +95,10 @@ class Router
|
||||
|
||||
|
||||
/**
|
||||
* Devuelve el ruta base o raiz del proyecto sobre la que trabajará el router.
|
||||
* Returns the base or root path of the project on which the router will work.
|
||||
*
|
||||
* Ej: Si la url del sistema está en "https://ejemplo.com/duckbrain"
|
||||
* entonces la ruta base sería "/duckbrain"
|
||||
* Ex: If the system URL is "https://example.com/duckbrain"
|
||||
* then the base path would be "/duckbrain"
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
@@ -94,14 +111,14 @@ class Router
|
||||
}
|
||||
|
||||
/**
|
||||
* Redirije a una ruta relativa interna.
|
||||
* Redirects to an internal relative path.
|
||||
*
|
||||
* @param string $path
|
||||
* La ruta relativa a la ruta base.
|
||||
* The path relative to the base path.
|
||||
*
|
||||
* Ej: Si nuesto sistema está en "https://ejemplo.com/duckbrain"
|
||||
* llamamos a Router::redirect('/docs'), entonces seremos
|
||||
* redirigidos a "https://ejemplo.com/duckbrain/docs".
|
||||
* Ex: If our system is at "https://example.com/duckbrain"
|
||||
* and we call Router::redirect('/docs'), we will be
|
||||
* redirected to "https://example.com/duckbrain/docs".
|
||||
* @return void
|
||||
*/
|
||||
public static function redirect(string $path): void
|
||||
@@ -111,14 +128,14 @@ class Router
|
||||
}
|
||||
|
||||
/**
|
||||
* Añade un middleware a la última ruta usada.
|
||||
* Solo se puede usar un middleware a la vez.
|
||||
* Adds a middleware to the last used route.
|
||||
* Only one middleware can be added at a time.
|
||||
*
|
||||
* @param callable $callback
|
||||
* @param int $prioriry
|
||||
* @param int $priority Optional priority for the middleware execution order.
|
||||
*
|
||||
* @return static
|
||||
* Devuelve la instancia actual.
|
||||
* Returns the current instance.
|
||||
*/
|
||||
public static function middleware(callable $callback, ?int $priority = null): static
|
||||
{
|
||||
@@ -147,7 +164,7 @@ class Router
|
||||
}
|
||||
|
||||
/**
|
||||
* Reconfigura el callback final de la última ruta.
|
||||
* Reconfigures the final callback of the last route.
|
||||
*
|
||||
* @param callable $callback
|
||||
*
|
||||
@@ -168,20 +185,20 @@ class Router
|
||||
}
|
||||
|
||||
/**
|
||||
* Configura calquier método para todas las rutas.
|
||||
* Configures any method for all routes.
|
||||
*
|
||||
* En caso de no recibir un callback, busca la ruta actual
|
||||
* solo configura la ruta como la última configurada
|
||||
* siempre y cuando la misma haya sido configurada previamente.
|
||||
* If no callback is received, it searches for the current route
|
||||
* and only sets the route as the last configured one
|
||||
* provided it has been configured previously.
|
||||
*
|
||||
* @param string $method
|
||||
* Método http.
|
||||
* HTTP method.
|
||||
* @param string $path
|
||||
* Ruta con pseudovariables.
|
||||
* Route with pseudovariables.
|
||||
* @param callable|null $callback
|
||||
*
|
||||
* @return
|
||||
* Devuelve la instancia actual.
|
||||
* @return static
|
||||
* Returns the current instance.
|
||||
*/
|
||||
public static function configure(string $method, string $path, ?callable $callback = null): static
|
||||
{
|
||||
@@ -209,15 +226,15 @@ class Router
|
||||
}
|
||||
|
||||
/**
|
||||
* Define los routers para el método GET.
|
||||
* Defines routers for the GET method.
|
||||
*
|
||||
* @param string $path
|
||||
* Ruta con pseudovariables.
|
||||
* Route with pseudovariables.
|
||||
* @param callable|null $callback
|
||||
* Callback que será llamado cuando la ruta configurada en $path coincida.
|
||||
* Callback that will be called when the route configured in $path matches.
|
||||
*
|
||||
* @return static
|
||||
* Devuelve la instancia actual.
|
||||
* Returns the current instance.
|
||||
*/
|
||||
public static function get(string $path, ?callable $callback = null): static
|
||||
{
|
||||
@@ -225,15 +242,15 @@ class Router
|
||||
}
|
||||
|
||||
/**
|
||||
* Define los routers para el método POST.
|
||||
* Defines routers for the POST method.
|
||||
*
|
||||
* @param string $path
|
||||
* Ruta con pseudovariables.
|
||||
* Route with pseudovariables.
|
||||
* @param callable|null $callback
|
||||
* Callback que será llamado cuando la ruta configurada en $path coincida.
|
||||
* Callback that will be called when the route configured in $path matches.
|
||||
*
|
||||
* @return static
|
||||
* Devuelve la instancia actual.
|
||||
* Returns the current instance.
|
||||
*/
|
||||
public static function post(string $path, ?callable $callback = null): static
|
||||
{
|
||||
@@ -241,15 +258,15 @@ class Router
|
||||
}
|
||||
|
||||
/**
|
||||
* Define los routers para el método PUT.
|
||||
* Defines routers for the PUT method.
|
||||
*
|
||||
* @param string $path
|
||||
* Ruta con pseudovariables.
|
||||
* Route with pseudovariables.
|
||||
* @param callable|null $callback
|
||||
* Callback que será llamado cuando la ruta configurada en $path coincida.
|
||||
* Callback that will be called when the route configured in $path matches.
|
||||
*
|
||||
* @return static
|
||||
* Devuelve la instancia actual
|
||||
* Returns the current instance
|
||||
*/
|
||||
|
||||
public static function put(string $path, ?callable $callback = null): static
|
||||
@@ -258,15 +275,15 @@ class Router
|
||||
}
|
||||
|
||||
/**
|
||||
* Define los routers para el método PATCH.
|
||||
* Defines routers for the PATCH method.
|
||||
*
|
||||
* @param string $path
|
||||
* Ruta con pseudovariables.
|
||||
* Route with pseudovariables.
|
||||
* @param callable|null $callback
|
||||
* Callback que será llamado cuando la ruta configurada en $path coincida.
|
||||
* Callback that will be called when the route configured in $path matches.
|
||||
*
|
||||
* @return static
|
||||
* Devuelve la instancia actual
|
||||
* Returns the current instance
|
||||
*/
|
||||
public static function patch(string $path, ?callable $callback = null): static
|
||||
{
|
||||
@@ -274,15 +291,15 @@ class Router
|
||||
}
|
||||
|
||||
/**
|
||||
* Define los routers para el método DELETE.
|
||||
* Defines routers for the DELETE method.
|
||||
*
|
||||
* @param string $path
|
||||
* Ruta con pseudovariables
|
||||
* Route with pseudovariables
|
||||
* @param callable|null $callback
|
||||
* Callback que será llamado cuando la ruta configurada en $path coincida.
|
||||
* Callback that will be called when the route configured in $path matches.
|
||||
*
|
||||
* @return static
|
||||
* Devuelve la instancia actual
|
||||
* Returns the current instance
|
||||
*/
|
||||
public static function delete(string $path, ?callable $callback = null): static
|
||||
{
|
||||
@@ -290,7 +307,7 @@ class Router
|
||||
}
|
||||
|
||||
/**
|
||||
* Devuelve la ruta actual tomando como raíz la ruta de instalación de DuckBrain.
|
||||
* Returns the current path, taking the DuckBrain installation path as the root.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
@@ -305,16 +322,16 @@ class Router
|
||||
}
|
||||
|
||||
/**
|
||||
* Aplica la configuración de rutas.
|
||||
* Applies the route configuration.
|
||||
*
|
||||
* @param string|null $path (opcional) Ruta a usar. Si no se define, detecta la ruta actual.
|
||||
* @param string|null $path (optional) Path to use. If not defined, it detects the current path.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function apply(?string $path = null): void
|
||||
{
|
||||
$path = $path ?? static::currentPath();
|
||||
$routers = match ($_SERVER['REQUEST_METHOD']) { // Según el método selecciona un arreglo de routers
|
||||
$routers = match ($_SERVER['REQUEST_METHOD']) { // Selects an array of routers based on the method
|
||||
'POST' => static::$post,
|
||||
'PUT' => static::$put,
|
||||
'PATCH' => static::$patch,
|
||||
@@ -322,11 +339,11 @@ class Router
|
||||
default => static::$get
|
||||
};
|
||||
|
||||
foreach ($routers as $router) { // revisa todos los routers para ver si coinciden con la ruta actual
|
||||
foreach ($routers as $router) { // Checks all routers to see if they match the current path
|
||||
if (preg_match_all('/^' . $router['path'] . '\/?$/si', $path, $matches, PREG_PATTERN_ORDER)) {
|
||||
unset($matches[0]);
|
||||
|
||||
// Comprobando y guardando los parámetros variables de la ruta
|
||||
// Checking and storing the variable parameters of the route
|
||||
if (isset($matches[1])) {
|
||||
foreach ($matches as $index => $match) {
|
||||
$paramName = $router['paramNames'][$index - 1];
|
||||
@@ -334,12 +351,12 @@ class Router
|
||||
}
|
||||
}
|
||||
|
||||
// Procesa la cola de callbacks
|
||||
// Processes the callback queue
|
||||
foreach (array_reverse($router['callback']) as $callback) {
|
||||
$data = Synapsis::resolve($callback);
|
||||
}
|
||||
|
||||
// Por defecto imprime como JSON si se retorna algo
|
||||
// By default, prints as JSON if something is returned
|
||||
if (isset($data)) {
|
||||
header('Content-Type: application/json');
|
||||
print(json_encode($data));
|
||||
@@ -349,7 +366,7 @@ class Router
|
||||
}
|
||||
}
|
||||
|
||||
// Si no hay router que coincida llamamos a $notFoundCallBack
|
||||
// If no router matches, call $notFoundCallBack
|
||||
Synapsis::resolve(static::$notFoundCallback);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user