Compare commits

..

6 Commits

6 changed files with 558 additions and 60 deletions

View File

@@ -2,6 +2,8 @@
namespace Libs;
use Exception;
/**
* Request - DuckBrain
*
@@ -59,17 +61,20 @@ class Request extends Neuron
}
// Run configured validations
if (!$this->validate()) {
exit();
}
$this->validate();
}
/**
* 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']) {
'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::rules(), $body)
) {
return true;
return;
}
$error = Validator::message(
@@ -98,7 +103,6 @@ class Request extends Neuron
);
static::onInvalid($error);
return false;
}
/**
@@ -157,27 +161,20 @@ class Request extends Neuron
/**
* Function to execute when an invalid value has been detected.
*
* Always answers with a single error and HTTP 422. The representation is
* negotiated from the request's Accept header: JSON when the client asks
* for application/json, plain text otherwise.
* The default implementation always throws a generic \Exception carrying
* the single error message and HTTP 422 as its code; the framework's
* 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
*
* @return void
* @return never
* @throws Exception
*/
public function onInvalid(string $error): void
public function onInvalid(string $error): never
{
http_response_code(422);
$accept = $_SERVER['HTTP_ACCEPT'] ?? '';
if (str_contains($accept, 'application/json')) {
header('Content-Type: application/json');
print(json_encode(['error' => $error]));
return;
}
print($error);
throw new Exception($error, 422);
}
}

View File

@@ -50,7 +50,7 @@ class Router
*
* @var callable $notFoundCallback
*/
public static $notFoundCallback = 'Libs\Router::defaultNotFound';
public static $notFoundCallback = Router::defaultNotFound(...);
/**
* Default callback function for when
@@ -64,6 +64,54 @@ class Router
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 = 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
*/
@@ -363,12 +411,19 @@ class Router
/**
* 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.
*
* @return void
*/
public static function apply(?string $path = null): void
{
try {
$path = $path ?? static::currentPath();
$routers = match ($_SERVER['REQUEST_METHOD']) { // Selects an array of routers based on the method
'POST' => static::$post,
@@ -408,5 +463,8 @@ class Router
// If no router matches, call $notFoundCallBack
Synapsis::resolve(static::$notFoundCallback);
} catch (\Throwable $exception) {
Synapsis::resolve(static::$exceptionCallback, ['exception' => $exception]);
}
}
}

View File

@@ -66,11 +66,13 @@ class Synapsis
* Resolves and injects dependencies for a callable and returns its result.
*
* @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
* @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
$reflectionCallback = new ReflectionFunction($action);
@@ -90,7 +92,7 @@ class Synapsis
// Get the parameters
return call_user_func_array(
$action,
static::resolveParameterValues($reflectionCallback->getParameters())
static::resolveParameterValues($reflectionCallback->getParameters(), $named)
);
}
@@ -132,11 +134,15 @@ class Synapsis
* Resolves parameter values by injecting dependencies.
*
* @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>
* @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 = [];
foreach ($parameters as $parameter) {
@@ -144,6 +150,11 @@ class Synapsis
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
$values[] = $parameter->getDefaultValue();
continue;

138
tests/Unit/RequestTest.php Normal file
View File

@@ -0,0 +1,138 @@
<?php
namespace Tests\Unit;
use Exception;
use Libs\Request;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
/**
* RequestTest - DuckBrain test harness
*
* Cubre el modelo de fallo por excepcion del Request: la validacion lanza
* con code 422 y el mensaje unico de Validator::message() (con overrides de
* messages()/attributes()), en lugar de responder HTTP y hacer exit() como
* hacia antes. Que estas pruebas puedan ejecutar expectException ya demuestra
* que el constructor no termina el proceso.
*/
final class RequestTest extends TestCase
{
private array $serverBackup = [];
private array $getBackup = [];
private array $postBackup = [];
protected function setUp(): void
{
$this->serverBackup = $_SERVER;
$this->getBackup = $_GET;
$this->postBackup = $_POST;
$_SERVER['REQUEST_METHOD'] = 'GET';
$_SERVER['REQUEST_URI'] = '/test';
$_SERVER['DOCUMENT_ROOT'] = '/nonexistent-docroot';
unset($_SERVER['CONTENT_TYPE'], $_SERVER['HTTP_ACCEPT']);
$_GET = [];
$_POST = [];
}
protected function tearDown(): void
{
$_SERVER = $this->serverBackup;
$_GET = $this->getBackup;
$_POST = $this->postBackup;
}
#[Test]
public function failedValidationThrowsWithHttp422Code(): void
{
$_SERVER['REQUEST_METHOD'] = 'POST';
$_POST = ['age' => '5'];
$this->expectException(Exception::class);
$this->expectExceptionMessage('The age must be at least 18.');
$this->expectExceptionCode(422);
new class extends Request {
public function rules(): array
{
return ['age' => 'required|min:18'];
}
};
}
#[Test]
public function messagesOverrideWinsForFailedRule(): void
{
$_SERVER['REQUEST_METHOD'] = 'POST';
$_POST = ['age' => '5'];
$this->expectException(Exception::class);
$this->expectExceptionMessage('Way too short');
new class extends Request {
public function rules(): array
{
return ['age' => 'required|min:18'];
}
public function messages(): array
{
return ['age.min' => 'Way too short'];
}
};
}
#[Test]
public function attributesRenameTheFieldInDefaultMessage(): void
{
$_SERVER['REQUEST_METHOD'] = 'POST';
$_POST = ['age' => '5'];
$this->expectException(Exception::class);
$this->expectExceptionMessage('The applicant age must be at least 18.');
new class extends Request {
public function rules(): array
{
return ['age' => 'required|min:18'];
}
public function attributes(): array
{
return ['age' => 'applicant age'];
}
};
}
#[Test]
public function getRulesFailureThrowsToo(): void
{
$this->expectException(Exception::class);
$this->expectExceptionMessage('The q field is required.');
new class extends Request {
public function getRules(): array
{
return ['q' => 'required'];
}
};
}
#[Test]
public function validDataDoesNotThrow(): void
{
$_SERVER['REQUEST_METHOD'] = 'POST';
$_POST = ['age' => '20'];
$request = new class extends Request {
public function rules(): array
{
return ['age' => 'required|min:18'];
}
};
$this->assertSame('20', $request->post->age);
$this->assertSame('/test', $request->path);
}
}

209
tests/Unit/RouterTest.php Normal file
View File

@@ -0,0 +1,209 @@
<?php
namespace Tests\Unit;
use Exception;
use Libs\Neuron;
use Libs\Router;
use LogicException;
use PDOException;
use PHPUnit\Framework\Attributes\Test;
use ReflectionProperty;
use Tests\TestCase;
use TypeError;
/**
* RouterTest - DuckBrain test harness
*
* Cubre la respuesta de error que produce Router::defaultException(): el
* status derivado del code de la excepcion con guard de rango 400-599 y la
* negociacion por Accept entre representacion JSON y texto plano. Tambien la
* frontera de Router::apply(): que toda excepcion de la cadena (middlewares,
* callback final, notFound) llegue al $exceptionCallback deteniendo la
* ejecucion sin exit() y dejando intacto el flujo normal.
*/
final class RouterTest extends TestCase
{
private array $serverBackup = [];
protected function setUp(): void
{
$this->serverBackup = $_SERVER;
$_SERVER['REQUEST_METHOD'] = 'GET';
unset($_SERVER['HTTP_ACCEPT']);
http_response_code(200);
$this->resetRouterState();
}
protected function tearDown(): void
{
$_SERVER = $this->serverBackup;
http_response_code(200);
$this->resetRouterState();
}
private function resetRouterState(): void
{
foreach (['get', 'post', 'put', 'patch', 'delete'] as $method) {
(new ReflectionProperty(Router::class, $method))->setValue(null, []);
}
Router::$params = new Neuron();
Router::$notFoundCallback = 'Libs\Router::defaultNotFound';
Router::$exceptionCallback = 'Libs\Router::defaultException';
}
private function render(\Throwable $exception): string
{
ob_start();
Router::defaultException($exception);
return ob_get_clean();
}
#[Test]
public function intCodeInHttpStatusRangeBecomesResponseStatus(): void
{
$output = $this->render(new Exception('The edad must be at least 18.', 422));
$this->assertSame(422, http_response_code());
$this->assertStringContainsString('The edad must be at least 18.', $output);
}
#[Test]
public function stringSqlStateCodeFallsBackToServerError(): void
{
$this->render(new PDOException('SQLSTATE[23000]: Integrity constraint violation', '23000'));
$this->assertSame(500, http_response_code(), 'A string SQLSTATE code must never reach http_response_code');
}
#[Test]
public function intCodeOutOfRangeFallsBackToServerError(): void
{
$this->render(new Exception('arbitrary code', 7));
$this->assertSame(500, http_response_code());
}
#[Test]
public function throwableWithoutMeaningfulCodeAnswersServerError(): void
{
$this->render(new TypeError('must be of the type int'));
$this->assertSame(500, http_response_code());
}
#[Test]
public function plainTextIsDefaultRepresentation(): void
{
$output = $this->render(new Exception('boom', 418));
$this->assertStringStartsWith("boom\n", $output);
$this->assertStringContainsString('#0', $output, 'Plain text must include the full trace');
}
#[Test]
public function jsonRepresentationWhenClientAcceptsJson(): void
{
$_SERVER['HTTP_ACCEPT'] = 'application/json';
$output = $this->render(new Exception('The e must be a valid email address.', 422));
$payload = json_decode($output, true);
$this->assertIsArray($payload, 'Accept: application/json must produce a JSON body');
$this->assertSame(422, http_response_code());
$this->assertSame('The e must be a valid email address.', $payload['error']);
$this->assertSame('Exception', $payload['exception']);
$this->assertArrayHasKey('file', $payload);
$this->assertArrayHasKey('line', $payload);
$this->assertIsArray($payload['trace']);
$this->assertIsString($payload['trace'][0], 'The trace must be serialized as readable lines, not raw frames');
}
#[Test]
public function middlewareExceptionStopsTheRemainingChain(): void
{
$log = [];
$caught = [];
Router::$exceptionCallback = function (\Throwable $exception) use (&$caught): void {
$caught[] = $exception;
};
Router::get('/chain', function () use (&$log): void {
$log[] = 'final';
});
Router::middleware(function () use (&$log): void {
$log[] = 'mw-late-registered';
});
Router::middleware(function () use (&$log): void {
throw new Exception('chain break', 422);
});
Router::middleware(function () use (&$log): void {
$log[] = 'mw-first-registered';
});
Router::apply('/chain');
// Callbacks run in reverse registration order: the last registered middleware
// ran first, the thrower stopped everything after it, and apply() returned
// normally (this line being reached proves there was no exit()).
$this->assertSame(['mw-first-registered'], $log);
$this->assertCount(1, $caught, 'The route chain must deliver exactly one exception to the callback');
$this->assertSame('chain break', $caught[0]->getMessage());
$this->assertSame(422, $caught[0]->getCode());
}
#[Test]
public function finalCallbackExceptionIsDeliveredToTheExceptionCallback(): void
{
$caught = [];
Router::$exceptionCallback = function (\Throwable $exception) use (&$caught): void {
$caught[] = get_class($exception) . ': ' . $exception->getMessage();
};
Router::get('/throwing', function (): void {
throw new LogicException('controller boom');
});
Router::apply('/throwing');
$this->assertSame(['LogicException: controller boom'], $caught);
}
#[Test]
public function notFoundCallbackExceptionReachesTheExceptionCallback(): void
{
$caught = [];
Router::$exceptionCallback = function (\Throwable $exception) use (&$caught): void {
$caught[] = $exception;
};
Router::$notFoundCallback = function (): void {
throw new Exception('not found exploded', 418);
};
Router::apply('/no-such-route');
$this->assertCount(1, $caught);
$this->assertSame('not found exploded', $caught[0]->getMessage());
$this->assertSame(418, $caught[0]->getCode());
}
#[Test]
public function normalFlowStillPrintsReturnedData(): void
{
Router::$exceptionCallback = function (): void {
$this->fail('The exception callback must not run on a successful request');
};
Router::get('/ok', function (): array {
return ['status' => 'ok'];
});
ob_start();
Router::apply('/ok');
$output = ob_get_clean();
$this->assertSame('{"status":"ok"}', $output);
$this->assertSame(200, http_response_code());
}
}

View File

@@ -0,0 +1,85 @@
<?php
namespace Tests\Unit;
use Exception;
use Libs\Neuron;
use Libs\Synapsis;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
/**
* SynapsisTest - DuckBrain test harness
*
* Cubre la inyeccion de argumentos por nombre en resolve(): la clave de
* $named gana sobre el default de un opcional y sobre la resolucion DI por
* tipo, la coincidencia es por nombre y no por posicion, y las claves
* sobrantes se ignoran en silencio (riesgo documentado en design.md).
*/
final class SynapsisTest extends TestCase
{
#[Test]
public function namedValueWinsOverOptionalDefault(): void
{
$result = Synapsis::resolve(
fn ($config = 'default') => $config,
['config' => 'forced']
);
$this->assertSame('forced', $result, 'A named argument must take precedence over an optional default');
}
#[Test]
public function namedValueWinsOverTypeBasedResolution(): void
{
$real = new Exception('the real one', 422);
$result = Synapsis::resolve(
fn (Exception $exception) => $exception,
['exception' => $real]
);
$this->assertSame($real, $result, 'The injected instance must be the named one, not a container-built empty Exception');
}
#[Test]
public function namedParametersMatchByNameNotPosition(): void
{
$real = new Exception('matched by name');
[$b, $exception] = Synapsis::resolve(
fn (Neuron $b, Exception $exception) => [$b, $exception],
['exception' => $real]
);
$this->assertInstanceOf(Neuron::class, $b, 'Parameters without a named match must keep resolving through DI');
$this->assertSame($real, $exception, 'Position of the named parameter must not matter');
}
#[Test]
public function unmatchedNamedKeysAreIgnored(): void
{
$result = Synapsis::resolve(
fn ($x = 'untouched') => $x,
['foo' => 1]
);
$this->assertSame('untouched', $result, 'A key matching no parameter must be silently ignored');
}
#[Test]
public function renamedParameterFallsBackToContainerResolution(): void
{
$real = new Exception('never arrives');
// The handler renamed its parameter to $e, so the 'exception' key
// matches nothing and $e degrades to DI: a fresh empty Exception.
$result = Synapsis::resolve(
fn (Exception $e) => $e,
['exception' => $real]
);
$this->assertNotSame($real, $result, 'A renamed handler parameter must not receive the named value');
$this->assertSame('', $result->getMessage(), 'The degradation outcome is a container-built empty Exception');
}
}