feat(router): replace middleware with before and after callbacks
This commit is contained in:
+162
-38
@@ -22,17 +22,26 @@ class Router
|
||||
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.
|
||||
* Stores a temporary stack of before callbacks to be applied to routes defined
|
||||
* within a specific scope, typically configured by `withBefore()`.
|
||||
* 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].
|
||||
* Used for chaining methods like middleware() or reconfigure().
|
||||
* Used for chaining methods like before(), after() or reconfigure().
|
||||
*
|
||||
* @var array $last
|
||||
*/
|
||||
@@ -129,9 +138,11 @@ class Router
|
||||
* Callback that will be called when the route configured in $path matches.
|
||||
*
|
||||
* @return array
|
||||
* Array with 3 indices:
|
||||
* Array with these indices:
|
||||
* 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.
|
||||
*/
|
||||
private static function parse(string $path, callable $callback): array
|
||||
@@ -148,7 +159,9 @@ class Router
|
||||
|
||||
return [
|
||||
'path' => $path,
|
||||
'callback' => [$callback],
|
||||
'callback' => $callback,
|
||||
'before' => [],
|
||||
'after' => [],
|
||||
'paramNames' => $paramNames,
|
||||
];
|
||||
}
|
||||
@@ -187,16 +200,47 @@ class Router
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a middleware to the last used route.
|
||||
* Only one middleware can be added at a time.
|
||||
* Inserts a callback into an ordered list of callback entries.
|
||||
*
|
||||
* 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 int|null $priority Optional priority for the middleware execution order.
|
||||
* @param int|null $priority Optional priority for the before execution order.
|
||||
*
|
||||
* @return static
|
||||
* 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)) {
|
||||
return new static();
|
||||
@@ -205,41 +249,86 @@ class Router
|
||||
$method = static::$last[0];
|
||||
$index = static::$last[1];
|
||||
|
||||
if (isset($priority) && $priority <= 0) {
|
||||
$priority = 1;
|
||||
}
|
||||
|
||||
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)
|
||||
static::$$method[$index]['before'] = static::insertOrdered(
|
||||
static::$$method[$index]['before'],
|
||||
$callback,
|
||||
$priority
|
||||
);
|
||||
}
|
||||
|
||||
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
|
||||
* Adds an after 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 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.
|
||||
*
|
||||
* @param callable $middleware
|
||||
* @param callable $before
|
||||
* @param callable $callback
|
||||
*
|
||||
* @return static
|
||||
*/
|
||||
public static function withMiddleware(callable $middleware, callable $callback): static
|
||||
public static function withBefore(callable $before, callable $callback): static
|
||||
{
|
||||
$currentMiddlewares = static::$withMiddlewares;
|
||||
array_unshift(static::$withMiddlewares, $middleware);
|
||||
$currentBefore = static::$withBefore;
|
||||
static::$withBefore[] = $before;
|
||||
|
||||
$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();
|
||||
}
|
||||
@@ -260,7 +349,7 @@ class Router
|
||||
$method = static::$last[0];
|
||||
$index = static::$last[1];
|
||||
|
||||
static::$$method[$index]['callback'][0] = $callback;
|
||||
static::$$method[$index]['callback'] = $callback;
|
||||
|
||||
return new static();
|
||||
}
|
||||
@@ -304,8 +393,12 @@ class Router
|
||||
static::$$method[] = static::parse($path, $callback);
|
||||
static::$last = [$method, count(static::$$method) - 1];
|
||||
|
||||
foreach (static::$withMiddlewares as $middleware) {
|
||||
static::middleware($middleware);
|
||||
foreach (static::$withBefore as $before) {
|
||||
static::before($before);
|
||||
}
|
||||
|
||||
foreach (static::$withAfter as $after) {
|
||||
static::after($after);
|
||||
}
|
||||
|
||||
return new static();
|
||||
@@ -445,16 +538,47 @@ class Router
|
||||
}
|
||||
}
|
||||
|
||||
// Processes the callback queue
|
||||
foreach (array_reverse($router['callback']) as $callback) {
|
||||
$data = Synapsis::resolve($callback);
|
||||
$hasAfter = !empty($router['after']);
|
||||
|
||||
if ($hasAfter) {
|
||||
ob_start();
|
||||
}
|
||||
|
||||
try {
|
||||
// Runs the before callbacks in FIFO order (higher priority first)
|
||||
foreach ($router['before'] as $entry) {
|
||||
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;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user