feat(router): replace middleware with before and after callbacks

This commit is contained in:
kj
2026-11-21 18:44:41 -03:00
parent 3b6da45b01
commit 3ec1cf48e1
+167 -43
View File
@@ -22,17 +22,26 @@ class Router
private static array $delete = []; private static array $delete = [];
/** /**
* Stores a temporary stack of middlewares to be applied to routes defined * Stores a temporary stack of before callbacks to be applied to routes defined
* within a specific scope, typically configured by `withMiddleware()`. * within a specific scope, typically configured by `withBefore()`.
* These middlewares are active only during the execution of the scope's callback. * These callbacks are active only during the execution of the scope's callback.
* *
* @var array $withMiddlewares<callable> * @var array $withBefore<callable>
*/ */
private static array $withMiddlewares = []; private static array $withBefore = [];
/**
* Stores a temporary stack of after callbacks to be applied to routes defined
* within a specific scope, typically configured by `withAfter()`.
* These callbacks are active only during the execution of the scope's callback.
*
* @var array $withAfter<callable>
*/
private static array $withAfter = [];
/** /**
* Stores the method and index of the last configured route, e.g., ['get', 0]. * Stores the method and index of the last configured route, e.g., ['get', 0].
* Used for chaining methods like middleware() or reconfigure(). * Used for chaining methods like before(), after() or reconfigure().
* *
* @var array $last * @var array $last
*/ */
@@ -129,9 +138,11 @@ class Router
* Callback that will be called when the route configured in $path matches. * Callback that will be called when the route configured in $path matches.
* *
* @return array * @return array
* Array with 3 indices: * Array with these indices:
* path - Contains the route with pseudovariables replaced by regular expressions. * path - Contains the route with pseudovariables replaced by regular expressions.
* callback - Contains the callback in Namespace\Class::Method format. * callback - Main callback of the route.
* before - Before callbacks (empty at parse time).
* after - After callbacks (empty at parse time).
* paramNames - An array of parameter names found in the path. * paramNames - An array of parameter names found in the path.
*/ */
private static function parse(string $path, callable $callback): array private static function parse(string $path, callable $callback): array
@@ -148,7 +159,9 @@ class Router
return [ return [
'path' => $path, 'path' => $path,
'callback' => [$callback], 'callback' => $callback,
'before' => [],
'after' => [],
'paramNames' => $paramNames, 'paramNames' => $paramNames,
]; ];
} }
@@ -187,16 +200,47 @@ class Router
} }
/** /**
* Adds a middleware to the last used route. * Inserts a callback into an ordered list of callback entries.
* Only one middleware can be added at a time. *
* Entries are kept in execution order: higher priorities first, callbacks
* without a priority last, and equal priorities in registration order.
*
* @param array<int, array{callback: callable, priority: int|null}> $entries
* @param callable $callback
* @param int|null $priority
*
* @return array<int, array{callback: callable, priority: int|null}>
*/
private static function insertOrdered(array $entries, callable $callback, ?int $priority): array
{
$position = count($entries);
foreach ($entries as $at => $entry) {
if (($entry['priority'] ?? PHP_INT_MIN) < ($priority ?? PHP_INT_MIN)) {
$position = $at;
break;
}
}
array_splice($entries, $position, 0, [['callback' => $callback, 'priority' => $priority]]);
return $entries;
}
/**
* Adds a before callback to the last used route.
* Only one callback can be added at a time.
*
* A higher priority runs earlier; callbacks without a priority run last,
* keeping their registration order.
* *
* @param callable $callback * @param callable $callback
* @param int|null $priority Optional priority for the middleware execution order. * @param int|null $priority Optional priority for the before execution order.
* *
* @return static * @return static
* Returns the current instance. * Returns the current instance.
*/ */
public static function middleware(callable $callback, ?int $priority = null): static public static function before(callable $callback, ?int $priority = null): static
{ {
if (!isset(static::$last)) { if (!isset(static::$last)) {
return new static(); return new static();
@@ -205,41 +249,86 @@ class Router
$method = static::$last[0]; $method = static::$last[0];
$index = static::$last[1]; $index = static::$last[1];
if (isset($priority) && $priority <= 0) { static::$$method[$index]['before'] = static::insertOrdered(
$priority = 1; static::$$method[$index]['before'],
} $callback,
$priority
if (is_null($priority) || $priority >= count(static::$$method[$index]['callback'])) { );
static::$$method[$index]['callback'][] = $callback;
} else {
static::$$method[$index]['callback'] = array_merge(
array_slice(static::$$method[$index]['callback'], 0, $priority),
[$callback],
array_slice(static::$$method[$index]['callback'], $priority)
);
}
return new static(); return new static();
} }
/** /**
* Temporarily applies a set of middlewares to routes defined within a given callback. * Adds an after callback to the last used route.
* The middlewares are only active for the duration of the callback execution * Only one callback can be added at a time.
*
* A higher priority runs earlier; callbacks without a priority run last,
* keeping their registration order.
*
* @param callable $callback
* @param int|null $priority Optional priority for the after execution order.
*
* @return static
* Returns the current instance.
*/
public static function after(callable $callback, ?int $priority = null): static
{
if (!isset(static::$last)) {
return new static();
}
$method = static::$last[0];
$index = static::$last[1];
static::$$method[$index]['after'] = static::insertOrdered(
static::$$method[$index]['after'],
$callback,
$priority
);
return new static();
}
/**
* Temporarily applies a set of before callbacks to routes defined within a given callback.
* The callbacks are only active for the duration of the callback execution
* and are reset afterwards. * and are reset afterwards.
* *
* @param callable $middleware * @param callable $before
* @param callable $callback * @param callable $callback
* *
* @return static * @return static
*/ */
public static function withMiddleware(callable $middleware, callable $callback): static public static function withBefore(callable $before, callable $callback): static
{ {
$currentMiddlewares = static::$withMiddlewares; $currentBefore = static::$withBefore;
array_unshift(static::$withMiddlewares, $middleware); static::$withBefore[] = $before;
$callback(); $callback();
static::$withMiddlewares = $currentMiddlewares; // Restore withMiddleware static::$withBefore = $currentBefore; // Restore withBefore
return new static();
}
/**
* Temporarily applies a set of after callbacks to routes defined within a given callback.
* The callbacks are only active for the duration of the callback execution
* and are reset afterwards.
*
* @param callable $after
* @param callable $callback
*
* @return static
*/
public static function withAfter(callable $after, callable $callback): static
{
$currentAfter = static::$withAfter;
static::$withAfter[] = $after;
$callback();
static::$withAfter = $currentAfter; // Restore withAfter
return new static(); return new static();
} }
@@ -260,7 +349,7 @@ class Router
$method = static::$last[0]; $method = static::$last[0];
$index = static::$last[1]; $index = static::$last[1];
static::$$method[$index]['callback'][0] = $callback; static::$$method[$index]['callback'] = $callback;
return new static(); return new static();
} }
@@ -304,8 +393,12 @@ class Router
static::$$method[] = static::parse($path, $callback); static::$$method[] = static::parse($path, $callback);
static::$last = [$method, count(static::$$method) - 1]; static::$last = [$method, count(static::$$method) - 1];
foreach (static::$withMiddlewares as $middleware) { foreach (static::$withBefore as $before) {
static::middleware($middleware); static::before($before);
}
foreach (static::$withAfter as $after) {
static::after($after);
} }
return new static(); return new static();
@@ -445,15 +538,46 @@ class Router
} }
} }
// Processes the callback queue $hasAfter = !empty($router['after']);
foreach (array_reverse($router['callback']) as $callback) {
$data = Synapsis::resolve($callback); if ($hasAfter) {
ob_start();
} }
// By default, prints as JSON if something is returned try {
if (isset($data)) { // Runs the before callbacks in FIFO order (higher priority first)
header('Content-Type: application/json'); foreach ($router['before'] as $entry) {
print(json_encode($data)); Synapsis::resolve($entry['callback']);
}
// Runs the main callback and keeps its return value
$data = Synapsis::resolve($router['callback']);
// By default, prints as JSON if something is returned
if (isset($data)) {
header('Content-Type: application/json');
print(json_encode($data));
}
} catch (\Throwable $thrown) {
if ($hasAfter) {
ob_end_clean();
}
throw $thrown;
}
if ($hasAfter) {
$response = ob_get_clean();
// Always use $response as parameter name in after to receive it.
foreach ($router['after'] as $entry) {
$replacement = Synapsis::resolve($entry['callback'], ['response' => $response]);
if (is_string($replacement)) {
$response = $replacement;
}
}
print($response);
} }
return; return;