From 78e199e300aaa8820dbf6833993f9ef6e3349065 Mon Sep 17 00:00:00 2001 From: kj Date: Sun, 1 Feb 2026 08:25:54 -0300 Subject: [PATCH] feat(router): Introduce withMiddleware() for scoped middlewares --- src/Libs/Router.php | 40 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/src/Libs/Router.php b/src/Libs/Router.php index 0ba4ccb..ff0588f 100644 --- a/src/Libs/Router.php +++ b/src/Libs/Router.php @@ -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 + */ + 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(); }