From 3acaacd3f5a088b913eb9f1948313cbd7329be04 Mon Sep 17 00:00:00 2001 From: mychidarko Date: Fri, 28 Apr 2023 15:11:45 +0000 Subject: [PATCH] feat: add registerMiddleware --- src/Router/Core.php | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/src/Router/Core.php b/src/Router/Core.php index 7c46d46..66b1707 100644 --- a/src/Router/Core.php +++ b/src/Router/Core.php @@ -30,7 +30,6 @@ class Core */ protected static $config = [ 'mode' => 'development', - 'debug' => true, 'app.down' => false, ]; @@ -51,6 +50,11 @@ class Core */ protected static $middleware = []; + /** + * Named middleware + */ + protected static $namedMiddleware = []; + /** * Route specific middleware */ @@ -152,6 +156,10 @@ protected static function mapHandler($handler, $options): array if (is_array($handler)) { $handlerData = $handler; + if (is_string($handler['middleware'] ?? null)) { + $handlerData['middleware'] = static::$namedMiddleware[$handler['middleware']] ?? null; + } + if (isset($handler['handler'])) { $handler = $handler['handler']; unset($handlerData['handler']); @@ -261,6 +269,17 @@ public static function use($newMiddleware) array_unshift(static::$middleware, $newMiddleware); } + /** + * Register a middleware in your Leaf application by name + * + * @param string $name The name of the middleware + * @param callable $middleware The middleware to register + */ + public function registerMiddleware(string $name, callable $middleware) + { + static::$namedMiddleware[$name] = $middleware; + } + /** * Return server base Path, and define it if isn't defined. * @@ -338,9 +357,8 @@ public static function run(?callable $callback = null) if (class_exists('Leaf\App')) { $config = array_merge($config, [ - 'mode' => \Leaf\Config::get('mode'), + 'mode' => \Leaf\Config::get('mode') ?? 'development', 'app.down' => \Leaf\Anchor::toBool(\Leaf\Config::get('app.down')) ?? false, - 'debug' => \Leaf\Anchor::toBool(\Leaf\Config::get('debug')) ?? false, ]); }