feat: initial commit of camelia/controllers

Framework-agnostic REST controller toolkit in vanilla PHP.

- Router with path parameters, 404 and 405 with an Allow header.
- Immutable Request, JsonRequest and Response; nothing is printed.
- CrudController over a ResourceGateway port the application implements.
- Composable Middleware/Pipeline chain.
- Security middlewares: BearerAuth, RequireRole, RateLimit, Cors.
- Transport middlewares: Logging, ContentNegotiation.
- Nine typed HTTP exceptions with snake_case JSON bodies.
- Declares PHP >=8.3 and no dependency on an ORM: ports are local.
- MIT license.
This commit is contained in:
dgarcia committed 2026-11-15 10:14:27 -03:00
commit 341d1bdc2c
52 files changed
+7552

No files matched your search

@@ -0,0 +1,113 @@
<?php
declare(strict_types=1);
namespace Camelia\Controllers\Tests\Unit\Middleware;
use Camelia\Controllers\JsonRequest;
use Camelia\Controllers\Middleware\ContentNegotiation;
use Camelia\Controllers\Request;
use Camelia\Controllers\Response;
use PHPUnit\Framework\TestCase;
final class ContentNegotiationTest extends TestCase
{
private static function ok(Request $request): Response
{
return new Response(['ok' => true]);
}
public function testAddsContentType(): void
{
$response = (new ContentNegotiation())->process(new JsonRequest(), self::ok(...));
self::assertSame(200, $response->status());
self::assertSame('application/json; charset=utf-8', $response->headers()['Content-Type']);
}
public function testMissingAcceptHeaderIsAccepted(): void
{
$response = (new ContentNegotiation())->process(new JsonRequest(), self::ok(...));
self::assertSame(200, $response->status());
}
public function testJsonAcceptIsAccepted(): void
{
$response = (new ContentNegotiation())->process(
new JsonRequest(headers: ['accept' => 'application/json']),
self::ok(...),
);
self::assertSame(200, $response->status());
}
public function testBrowserAcceptIsAccepted(): void
{
$accept = 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8';
$response = (new ContentNegotiation())->process(
new JsonRequest(headers: ['accept' => $accept]),
self::ok(...),
);
self::assertSame(200, $response->status());
}
public function testIncompatibleAcceptIs406(): void
{
$response = (new ContentNegotiation())->process(
new JsonRequest(headers: ['accept' => 'application/xml']),
static function (): Response {
self::fail('The handler must not run when the client rejects JSON.');
},
);
self::assertSame(406, $response->status());
self::assertSame('not_acceptable', $response->body()['code']);
}
public function testZeroQualityIsRejected(): void
{
$response = (new ContentNegotiation())->process(
new JsonRequest(headers: ['accept' => 'application/json;q=0']),
static function (): Response {
self::fail('A q=0 entry means not acceptable.');
},
);
self::assertSame(406, $response->status());
}
public function testNonZeroQualityIsAccepted(): void
{
$response = (new ContentNegotiation())->process(
new JsonRequest(headers: ['accept' => 'application/json;q=0.5']),
self::ok(...),
);
self::assertSame(200, $response->status());
}
public function testExistingContentTypeIsPreserved(): void
{
$response = (new ContentNegotiation())->process(
new JsonRequest(),
static fn(): Response => new Response(['ok' => true], 200, [
'Content-Type' => 'application/problem+json',
]),
);
self::assertSame('application/problem+json', $response->headers()['Content-Type']);
}
public function testContentTypeCanBeDisabled(): void
{
$response = (new ContentNegotiation(addContentType: false))->process(
new JsonRequest(),
self::ok(...),
);
self::assertFalse($response->hasHeader('Content-Type'));
}
}
+116
View File
@@ -0,0 +1,116 @@
<?php
declare(strict_types=1);
namespace Camelia\Controllers\Tests\Unit\Middleware;
use Camelia\Controllers\JsonRequest;
use Camelia\Controllers\Middleware\Logging;
use Camelia\Controllers\Request;
use Camelia\Controllers\Response;
use PHPUnit\Framework\TestCase;
final class LoggingTest extends TestCase
{
/** @var list<array{level: string, message: string, context: array<string, mixed>}> */
private array $logs = [];
private float $now = 100.0;
private function logging(): Logging
{
return new Logging(
function (string $level, string $message, array $context): void {
$this->logs[] = ['level' => $level, 'message' => $message, 'context' => $context];
},
fn(): float => $this->now,
);
}
private static function ok(Request $request): Response
{
return new Response(['ok' => true]);
}
public function testRecordsSuccessfulRequest(): void
{
$response = $this->logging()->process(
new JsonRequest(method: 'GET', path: '/articulos'),
self::ok(...),
);
self::assertSame(200, $response->status());
self::assertCount(1, $this->logs);
self::assertSame('info', $this->logs[0]['level']);
self::assertSame('GET /articulos 200', $this->logs[0]['message']);
self::assertSame('/articulos', $this->logs[0]['context']['path']);
self::assertSame(200, $this->logs[0]['context']['status']);
}
public function testClientErrorLogsWarning(): void
{
$this->logging()->process(
new JsonRequest(path: '/x'),
static fn(): Response => new Response(['e' => 1], 404),
);
self::assertSame('warning', $this->logs[0]['level']);
}
public function testServerErrorLogsError(): void
{
$this->logging()->process(
new JsonRequest(path: '/x'),
static fn(): Response => new Response(null, 500),
);
self::assertSame('error', $this->logs[0]['level']);
}
public function testDurationIsMeasured(): void
{
$reads = [100.0, 120.5, 120.5, 163.0];
$logging = new Logging(function (string $level, string $message, array $context): void {
$this->logs[] = ['level' => $level, 'message' => $message, 'context' => $context];
}, static function () use (&$reads): float {
return (float) array_shift($reads);
});
$logging->process(new JsonRequest(), static fn(): Response => new Response(null));
self::assertSame(20.5, $this->logs[0]['context']['duration_ms']);
$logging->process(new JsonRequest(), static fn(): Response => new Response(null));
self::assertSame(42.5, $this->logs[1]['context']['duration_ms']);
}
public function testThrowableIsLoggedAndRethrown(): void
{
$logging = $this->logging();
try {
$logging->process(new JsonRequest(path: '/boom'), static function (): Response {
throw new \RuntimeException('exploded');
});
self::fail('The exception must propagate: the router owns error mapping.');
} catch (\RuntimeException $exception) {
self::assertSame('exploded', $exception->getMessage());
}
self::assertCount(1, $this->logs);
self::assertSame(500, $this->logs[0]['context']['status']);
self::assertSame('error', $this->logs[0]['level']);
}
public function testReturnsHandlerResponseUnchanged(): void
{
$original = new Response(['x' => 1], 201, ['Location' => '/a/1']);
$response = $this->logging()->process(
new JsonRequest(),
static fn(): Response => $original,
);
self::assertSame($original, $response);
}
}