feat(router): Introduce withMiddleware() for scoped middlewares

This commit is contained in:
kj
2026-02-01 08:25:54 -03:00
parent 8cd5e114dd
commit 78e199e300

View File

@@ -21,6 +21,15 @@ class Router
private static array $patch = [];
private static array $delete = [];
/**
* Stores a temporary stack of middlewares to be applied to routes defined
* within a specific scope, typically configured by `withMiddleware()`.
* These middlewares are active only during the execution of the scope's callback.
*
* @var array $withMiddlewares<callable>
*/
private static array $withMiddlewares = [];
/**
* Stores the method and index of the last configured route, e.g., ['get', 0].
* Used for chaining methods like middleware() or reconfigure().
@@ -166,6 +175,28 @@ class Router
return new static();
}
/**
* Temporarily applies a set of middlewares to routes defined within a given callback.
* The middlewares are only active for the duration of the callback execution
* and are reset afterwards.
*
* @param callable $middleware
* @param callable $callback
*
* @return static
*/
public static function withMiddleware(callable $middleware, callable $callback): static
{
$currentMiddlewares = static::$withMiddlewares;
array_unshift(static::$withMiddlewares, $middleware);
$callback();
static::$withMiddlewares = $currentMiddlewares; // Restore withMiddleware
return new static();
}
/**
* Reconfigures the final callback of the last route.
*
@@ -201,7 +232,7 @@ class Router
* @param callable|null $callback
*
* @return static
* Returns the current instance.
* Returns the current instance.
*/
public static function configure(string $method, string $path, ?callable $callback = null): static
{
@@ -225,6 +256,13 @@ class Router
static::$$method[] = static::parse($path, $callback);
static::$last = [$method, count(static::$$method) - 1];
if (count(static::$withMiddlewares) > 0) {
foreach (static::$withMiddlewares as $middleware) {
static::middleware($middleware);
}
}
return new static();
}