Skip to content

Commit

Permalink
feat: add registerMiddleware
Browse files Browse the repository at this point in the history
  • Loading branch information
mychidarko committed Apr 28, 2023
1 parent 546ab8e commit 3acaacd
Showing 1 changed file with 21 additions and 3 deletions.
24 changes: 21 additions & 3 deletions src/Router/Core.php
Expand Up @@ -30,7 +30,6 @@ class Core
*/
protected static $config = [
'mode' => 'development',
'debug' => true,
'app.down' => false,
];

Expand All @@ -51,6 +50,11 @@ class Core
*/
protected static $middleware = [];

/**
* Named middleware
*/
protected static $namedMiddleware = [];

/**
* Route specific middleware
*/
Expand Down Expand Up @@ -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']);
Expand Down Expand Up @@ -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.
*
Expand Down Expand Up @@ -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,
]);
}

Expand Down

0 comments on commit 3acaacd

Please sign in to comment.