7 Commits
Author SHA1 Message Date
kj 3ec1cf48e1 feat(router): replace middleware with before and after callbacks 2026-11-21 18:44:41 -03:00
kj 3b6da45b01 refactor(validator): rename enum rule and method to in 2026-09-14 16:48:02 -03:00
kj b7260b5199 refactor(Router): use string callable syntax for default callbacks 2026-09-08 12:08:32 -03:00
kj 1f29622914 refactor(router): remove exit statement from redirect method 2026-09-07 20:00:15 -03:00
kj eb882db0c8 sync: 2026-09-07
70b1016 refactor(autoload): remove global exception handler
a534613 refactor(request): propagate validation failures as exceptions
5f3fc16 feat(router): add error boundary with exception callback
9dbfd7d feat: add named parameter injection to resolve()
2026-09-07 18:00:18 -03:00
kj 9ba43e3f25 sync: 2026-09-05
25db49f fix(model): reset query state when database query fails
9cb41d5 fix(model): use RANDOM() for non-MySQL databases in orderBy
2026-09-05 16:49:10 -03:00
kj 54e96ba4bb sync: first sync with the new develop branch
a4611e8 chore(src): rename .keep files to .gitkeep
2026-09-05 14:21:52 -03:00
11 changed files with 300 additions and 110 deletions
-5
View File
@@ -12,8 +12,3 @@ spl_autoload_register(function ($className) {
require_once $file; require_once $file;
} }
}); });
set_exception_handler(function ($exception) {
echo "Uncaught exception: " , $exception->getMessage(), "\n";
echo $exception->getTraceAsString();
});
+7 -1
View File
@@ -176,6 +176,10 @@ class Model
$vars = json_encode(static::$dbQueryVariables); $vars = json_encode(static::$dbQueryVariables);
if ($resetQuery) {
static::resetQuery();
}
throw new Exception( throw new Exception(
"\nError at query to database.\n" . "\nError at query to database.\n" .
"Query: $query\n" . "Query: $query\n" .
@@ -1008,7 +1012,9 @@ class Model
public static function orderBy(string $value, string $order = 'ASC'): static public static function orderBy(string $value, string $order = 'ASC'): static
{ {
if ($value == "RAND") { if ($value == "RAND") {
static::$dbQuery['orderBy'] = 'RAND()'; $random = static::db()->getAttribute(PDO::ATTR_DRIVER_NAME) == 'mysql' ? 'RAND()' : 'RANDOM()';
static::$dbQuery['orderBy'] = $random;
return new static(); return new static();
} }
+21 -24
View File
@@ -2,6 +2,8 @@
namespace Libs; namespace Libs;
use Exception;
/** /**
* Request - DuckBrain * Request - DuckBrain
* *
@@ -59,17 +61,20 @@ class Request extends Neuron
} }
// Run configured validations // Run configured validations
if (!$this->validate()) { $this->validate();
exit();
}
} }
/** /**
* Starts the configured validation. * Starts the configured validation.
* *
* @return bool * On failure the single error message is built with Validator::message()
* and handed to onInvalid(), which throws by default: failures travel up
* as exceptions instead of answering HTTP here.
*
* @return void
* @throws Exception When a configured rule fails.
*/ */
public function validate(): bool public function validate(): void
{ {
$actual = match ($_SERVER['REQUEST_METHOD']) { $actual = match ($_SERVER['REQUEST_METHOD']) {
'POST', 'PUT', 'PATCH', 'DELETE' => $this->{strtolower($_SERVER['REQUEST_METHOD'])}, 'POST', 'PUT', 'PATCH', 'DELETE' => $this->{strtolower($_SERVER['REQUEST_METHOD'])},
@@ -88,7 +93,7 @@ class Request extends Neuron
Validator::validateList(static::getRules(), $this->get) && Validator::validateList(static::getRules(), $this->get) &&
Validator::validateList(static::rules(), $body) Validator::validateList(static::rules(), $body)
) { ) {
return true; return;
} }
$error = Validator::message( $error = Validator::message(
@@ -98,7 +103,6 @@ class Request extends Neuron
); );
static::onInvalid($error); static::onInvalid($error);
return false;
} }
/** /**
@@ -157,27 +161,20 @@ class Request extends Neuron
/** /**
* Function to execute when an invalid value has been detected. * Function to execute when an invalid value has been detected.
* *
* Always answers with a single error and HTTP 422. The representation is * The default implementation always throws a generic \Exception carrying
* negotiated from the request's Accept header: JSON when the client asks * the single error message and HTTP 422 as its code; the framework's
* for application/json, plain text otherwise. * exception boundary (Router::apply) renders the response. Override it to
* throw a more specific exception type instead. The never return type is
* the contract: an override that returned would let the request continue
* with invalid data, so PHP rejects such an override at compile time.
* *
* @param string $error * @param string $error
* *
* @return void * @return never
* @throws Exception
*/ */
public function onInvalid(string $error): void public function onInvalid(string $error): never
{ {
http_response_code(422); throw new Exception($error, 422);
$accept = $_SERVER['HTTP_ACCEPT'] ?? '';
if (str_contains($accept, 'application/json')) {
header('Content-Type: application/json');
print(json_encode(['error' => $error]));
return;
}
print($error);
} }
} }
+220 -39
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
*/ */
@@ -64,6 +73,54 @@ class Router
echo '<h2 style="text-align: center;margin: 25px 0px;">Error 404 - Page Not Found</h2>'; echo '<h2 style="text-align: center;margin: 25px 0px;">Error 404 - Page Not Found</h2>';
} }
/**
* The callback function to be executed when the router's boundary
* catches an exception thrown anywhere in the matched route chain.
* It receives the exception as a named argument: the handler must
* declare its parameter as $exception (typeable as \Throwable).
*
* @var callable $exceptionCallback
*/
public static $exceptionCallback = 'Libs\Router::defaultException';
/**
* Default callback function for exception responses.
*
* The HTTP status comes from the exception's code only when it is an
* integer in the 400-599 range; anything else (0, arbitrary codes, the
* SQLSTATE string carried by PDOException) answers 500. The body is
* negotiated from the request's Accept header: JSON when the client asks
* for application/json, plain text otherwise. The trace is serialized
* from getTraceAsString() because json_encode() of a Throwable yields an
* empty object: its properties are protected.
*
* @param \Throwable $exception
*
* @return void
*/
public static function defaultException(\Throwable $exception): void
{
$code = $exception->getCode();
http_response_code(is_int($code) && $code >= 400 && $code <= 599 ? $code : 500);
$accept = $_SERVER['HTTP_ACCEPT'] ?? '';
if (str_contains($accept, 'application/json')) {
header('Content-Type: application/json');
print(json_encode([
'error' => $exception->getMessage(),
'exception' => get_class($exception),
'file' => $exception->getFile(),
'line' => $exception->getLine(),
'trace' => explode(PHP_EOL, $exception->getTraceAsString()),
]));
return;
}
print($exception->getMessage() . PHP_EOL . $exception->getTraceAsString());
}
/** /**
* __construct * __construct
*/ */
@@ -81,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
@@ -100,7 +159,9 @@ class Router
return [ return [
'path' => $path, 'path' => $path,
'callback' => [$callback], 'callback' => $callback,
'before' => [],
'after' => [],
'paramNames' => $paramNames, 'paramNames' => $paramNames,
]; ];
} }
@@ -136,20 +197,50 @@ class Router
public static function redirect(string $path): void public static function redirect(string $path): void
{ {
header('Location: ' . static::basePath() . ltrim($path, '/')); header('Location: ' . static::basePath() . ltrim($path, '/'));
exit;
} }
/** /**
* 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();
@@ -158,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();
} }
@@ -213,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();
} }
@@ -257,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();
@@ -363,12 +503,19 @@ class Router
/** /**
* Applies the route configuration. * Applies the route configuration.
* *
* This method is the framework's error boundary: any \Throwable thrown
* while running the matched route's callback chain, while printing the
* returned data, or while resolving the not-found callback is caught
* here and rendered through $exceptionCallback. A failing handler is
* deliberately left uncaught (double failure falls back to PHP itself).
*
* @param string|null $path (optional) Path to use. If not defined, it detects the current path. * @param string|null $path (optional) Path to use. If not defined, it detects the current path.
* *
* @return void * @return void
*/ */
public static function apply(?string $path = null): void public static function apply(?string $path = null): void
{ {
try {
$path = $path ?? static::currentPath(); $path = $path ?? static::currentPath();
$routers = match ($_SERVER['REQUEST_METHOD']) { // Selects an array of routers based on the method $routers = match ($_SERVER['REQUEST_METHOD']) { // Selects an array of routers based on the method
'POST' => static::$post, 'POST' => static::$post,
@@ -391,16 +538,47 @@ 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();
} }
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 // By default, prints as JSON if something is returned
if (isset($data)) { if (isset($data)) {
header('Content-Type: application/json'); header('Content-Type: application/json');
print(json_encode($data)); 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;
} }
@@ -408,5 +586,8 @@ class Router
// If no router matches, call $notFoundCallBack // If no router matches, call $notFoundCallBack
Synapsis::resolve(static::$notFoundCallback); Synapsis::resolve(static::$notFoundCallback);
} catch (\Throwable $exception) {
Synapsis::resolve(static::$exceptionCallback, ['exception' => $exception]);
}
} }
} }
+14 -3
View File
@@ -66,11 +66,13 @@ class Synapsis
* Resolves and injects dependencies for a callable and returns its result. * Resolves and injects dependencies for a callable and returns its result.
* *
* @param callable $action * @param callable $action
* @param array<string, mixed> $named Associative array of values injected into the callable's
* parameters by exact name match. Consumed in resolveParameterValues().
* *
* @return mixed * @return mixed
* @throws Exception If an unhandled callable type is provided. * @throws Exception If an unhandled callable type is provided.
*/ */
public static function resolve(callable $action): mixed public static function resolve(callable $action, array $named = []): mixed
{ {
if ($action instanceof Closure) { // If it's an anonymous function if ($action instanceof Closure) { // If it's an anonymous function
$reflectionCallback = new ReflectionFunction($action); $reflectionCallback = new ReflectionFunction($action);
@@ -90,7 +92,7 @@ class Synapsis
// Get the parameters // Get the parameters
return call_user_func_array( return call_user_func_array(
$action, $action,
static::resolveParameterValues($reflectionCallback->getParameters()) static::resolveParameterValues($reflectionCallback->getParameters(), $named)
); );
} }
@@ -132,11 +134,15 @@ class Synapsis
* Resolves parameter values by injecting dependencies. * Resolves parameter values by injecting dependencies.
* *
* @param array<ReflectionParameter> $parameters * @param array<ReflectionParameter> $parameters
* @param array<string, mixed> $named
* Values injected into parameters whose name matches the key,
* taking precedence over optional defaults and DI resolution.
* Keys matching no parameter are ignored.
* *
* @return array<mixed> * @return array<mixed>
* @throws Exception If a primitive parameter does not have a default value. * @throws Exception If a primitive parameter does not have a default value.
*/ */
public static function resolveParameterValues(array $parameters): array public static function resolveParameterValues(array $parameters, array $named = []): array
{ {
$values = []; $values = [];
foreach ($parameters as $parameter) { foreach ($parameters as $parameter) {
@@ -144,6 +150,11 @@ class Synapsis
continue; continue;
} }
if (array_key_exists($parameter->getName(), $named)) { // Named values win over defaults and DI
$values[] = $named[$parameter->getName()];
continue;
}
if ($parameter->isOptional()) { // Always use the default value first if ($parameter->isOptional()) { // Always use the default value first
$values[] = $parameter->getDefaultValue(); $values[] = $parameter->getDefaultValue();
continue; continue;
+7 -7
View File
@@ -38,7 +38,7 @@ use Exception;
* | url | | Must be a valid URL | * | url | | Must be a valid URL |
* | date | | Must be a parseable date | * | date | | Must be a parseable date |
* | regex | :pattern | Must match a PCRE pattern (with delimiters) | * | regex | :pattern | Must match a PCRE pattern (with delimiters) |
* | enum | :a,b,c | Must be one of the listed values | * | in | :a,b,c | Must be one of the listed values |
* | min | :n | Length/number/count min (files: KB) | * | min | :n | Length/number/count min (files: KB) |
* | max | :n | Length/number/count max (files: KB) | * | max | :n | Length/number/count max (files: KB) |
* | between | :min,:max | Value within range (files: KB per upload) | * | between | :min,:max | Value within range (files: KB per upload) |
@@ -105,7 +105,7 @@ class Validator
* | :size | the size rule value | * | :size | the size rule value |
* | :value | the required_if expected value | * | :value | the required_if expected value |
* | :other | the required_if companion field / confirmation | * | :other | the required_if companion field / confirmation |
* | :values | a comma list (enum, mimes, required_with) | * | :values | a comma list (in, mimes, required_with) |
* |----------+----------------------------------------------------| * |----------+----------------------------------------------------|
* *
* @var array<string,string> * @var array<string,string>
@@ -122,7 +122,7 @@ class Validator
'array' => 'The :attribute must be an array.', 'array' => 'The :attribute must be an array.',
'email' => 'The :attribute must be a valid email address.', 'email' => 'The :attribute must be a valid email address.',
'url' => 'The :attribute must be a valid URL.', 'url' => 'The :attribute must be a valid URL.',
'enum' => 'The selected :attribute is invalid. Allowed: :values.', 'in' => 'The selected :attribute is invalid. Allowed: :values.',
'min' => 'The :attribute must be at least :min.', 'min' => 'The :attribute must be at least :min.',
'max' => 'The :attribute must not be greater than :max.', 'max' => 'The :attribute must not be greater than :max.',
'between' => 'The :attribute must be between :min and :max.', 'between' => 'The :attribute must be between :min and :max.',
@@ -243,7 +243,7 @@ class Validator
case 'size': case 'size':
$replace[':size'] = $args[0] ?? ''; $replace[':size'] = $args[0] ?? '';
break; break;
case 'enum': case 'in':
case 'mimes': case 'mimes':
case 'required_with': case 'required_with':
$replace[':values'] = implode(', ', $args); $replace[':values'] = implode(', ', $args);
@@ -305,7 +305,7 @@ class Validator
* arguments legitimately contain ':' or ',' - such as regex or mimes - * arguments legitimately contain ':' or ',' - such as regex or mimes -
* are preserved intact. The caller decides how to split the arguments. * are preserved intact. The caller decides how to split the arguments.
* *
* @param string $rule The rule to parse. Ex: "regex:/^a,b$/" or "enum:a,b". * @param string $rule The rule to parse. Ex: "regex:/^a,b$/" or "in:a,b".
* *
* @return array A two element array: [name, rawArguments]. When the rule * @return array A two element array: [name, rawArguments]. When the rule
* has no parameters, rawArguments is an empty string. * has no parameters, rawArguments is an empty string.
@@ -419,7 +419,7 @@ class Validator
* Splits a rule's raw argument string into the arguments to pass to the * Splits a rule's raw argument string into the arguments to pass to the
* rule's method (the subject is not included). * rule's method (the subject is not included).
* *
* Most rules take a comma-separated list of values (e.g. "enum:a,b"). * Most rules take a comma-separated list of values (e.g. "in:a,b").
* A few rules receive an argument that must be kept intact because it can * A few rules receive an argument that must be kept intact because it can
* legitimately contain commas or colons: "regex" (a pattern) and "not" * legitimately contain commas or colons: "regex" (a pattern) and "not"
* (a sub-rule that is itself parsed recursively). An empty argument string * (a sub-rule that is itself parsed recursively). An empty argument string
@@ -810,7 +810,7 @@ class Validator
* *
* @return bool * @return bool
*/ */
public static function enum(mixed $subject, ...$values): bool public static function in(mixed $subject, ...$values): bool
{ {
return in_array($subject, $values); return in_array($subject, $values);
} }