Files
dgarcia 341d1bdc2c 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.
2026-11-15 10:14:27 -03:00

548 lines
14 KiB
Markdown

# Ejemplos — una API de facturación de punta a punta
Una aplicación completa y funcional: artículos, clientes y facturas, con seguridad, paginación y
tests. Todo el código es ejecutable tal cual.
## Estructura
```
app/
├── index.php punto de entrada
├── Gateway/
│ ├── ArticuloGateway.php adaptador sobre camelia/orm
│ └── ClienteGateway.php
└── Http/
├── ArticuloController.php
└── ClienteController.php
tests/
└── ApiTest.php
```
---
## 1. El punto de entrada
`app/index.php` traduce el entorno web a `Request`, despacha y emite. Es la **única** parte de la app
que toca superglobales.
```php
<?php
declare(strict_types=1);
require __DIR__ . '/../vendor/autoload.php';
use App\Gateway\ArticuloGateway;
use App\Gateway\ClienteGateway;
use App\Http\ArticuloController;
use App\Http\ClienteController;
use App\Model\Articulo;
use App\Model\Cliente;
use App\Support\Jwt;
use Camelia\Controllers\Exception\Unauthorized;
use Camelia\Controllers\JsonRequest;
use Camelia\Controllers\Middleware\ContentNegotiation;
use Camelia\Controllers\Middleware\Logging;
use Camelia\Controllers\Router;
use Camelia\Controllers\Security\BearerAuth;
use Camelia\Controllers\Security\Cors;
use Camelia\Controllers\Security\RateLimit;
use Camelia\Orm\Orm;
// --- 1. Infraestructura -------------------------------------------------
$orm = Orm::fromEnvironment();
$articulos = new ArticuloController(new ArticuloGateway($orm->repository(Articulo::class)));
$clientes = new ClienteController(new ClienteGateway($orm->repository(Cliente::class)));
// --- 2. Verificación del token (decisión de la app) ----------------------
$verify = static function (string $token): ?array {
try {
return Jwt::decode($token, getenv('JWT_SECRET'));
} catch (\Throwable) {
return null;
}
};
// --- 3. Router con la cadena completa ------------------------------------
$router = (new Router())
->withMiddleware(new ContentNegotiation())
->withMiddleware(new Cors(allowedOrigins: [getenv('APP_ORIGIN') ?: '*']))
->withMiddleware(new RateLimit(limit: 120, windowSeconds: 60))
->withMiddleware(new BearerAuth($verify))
->withMiddleware(new Logging(static function (string $level, string $message, array $context): void {
error_log(sprintf('[%s] %s %s', $level, $message, json_encode($context)));
}));
$router
->get('/articulos', $articulos)
->post('/articulos', $articulos)
->get('/articulos/{id}', $articulos)
->put('/articulos/{id}', $articulos)
->delete('/articulos/{id}', $articulos)
->get('/clientes', $clientes)
->post('/clientes', $clientes)
->get('/clientes/{id}', $clientes)
->delete('/clientes/{id}', $clientes);
// --- 4. Traducción del entorno ------------------------------------------
$headers = [];
foreach ($_SERVER as $key => $value) {
// HTTP_ORIGIN => origin, HTTP_X_TRACE_ID => x-trace-id
if (str_starts_with($key, 'HTTP_')) {
$headers[strtolower(str_replace('_', '-', substr($key, 5)))] = (string) $value;
}
}
$request = new JsonRequest(
method: $_SERVER['REQUEST_METHOD'] ?? 'GET',
path: parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/',
query: $_GET,
body: json_decode(file_get_contents('php://input') ?: '{}', true) ?: [],
headers: $headers,
);
// --- 5. Emisión ---------------------------------------------------------
$response = $router->dispatch($request);
http_response_code($response->status());
foreach ($response->headers() as $name => $value) {
header($name . ': ' . $value);
}
echo $response->toJson();
```
> **Por qué el `foreach` de cabeceras.** PHP entrega cada cabecera como `HTTP_<NOMBRE>` con guiones
> bajos. `JsonRequest::header()` ya compara en minúsculas, así que ese bucle es toda la normalización
> necesaria.
---
## 2. Controllers
Solo declaran el recurso. Toda la lógica REST vive en `CrudController`.
```php
<?php
declare(strict_types=1);
namespace App\Http;
use App\Gateway\ArticuloGateway;
use Camelia\Controllers\CrudController;
final class ArticuloController extends CrudController
{
public function __construct(ArticuloGateway $gateway)
{
parent::__construct($gateway, 'articulos');
}
}
```
```php
<?php
declare(strict_types=1);
namespace App\Http;
use App\Gateway\ClienteGateway;
use Camelia\Controllers\CrudController;
final class ClienteController extends CrudController
{
public function __construct(ClienteGateway $gateway)
{
parent::__construct($gateway, 'clientes');
}
}
```
---
## 3. Adaptadores de ORM
Aquí vive el acoplamiento, y solo aquí.
```php
<?php
declare(strict_types=1);
namespace App\Gateway;
use Camelia\Controllers\ResourceGateway;
use Camelia\Orm\Model;
use Camelia\Orm\Repository;
/**
* @template T of Model
*/
abstract class OrmGateway implements ResourceGateway
{
/**
* @param Repository<T> $repository
*/
public function __construct(protected readonly Repository $repository) {}
public function findAll(array $query = []): array
{
$perPage = max(1, min(1000, (int) ($query['per_page'] ?? 20)));
$page = max(1, (int) ($query['page'] ?? 1));
$items = $this->repository->find(
order: $this->orderFrom($query),
limit: $perPage,
offset: ($page - 1) * $perPage,
);
return array_map($this->toArray(...), $items);
}
public function find(int|string $id): ?array
{
$model = $this->repository->findByPk($id);
return $model === null ? null : $this->toArray($model);
}
public function create(array $values): array
{
return $this->toArray($this->repository->create($values));
}
public function update(int|string $id, array $values): ?array
{
$model = $this->repository->findByPk($id);
if ($model === null) {
return null;
}
$model->assign($values);
$this->repository->save($model);
return $this->toArray($model);
}
public function delete(int|string $id): bool
{
return $this->repository->remove($id) > 0;
}
public function count(array $query = []): ?int
{
return $this->repository->count();
}
/** @return array<string, mixed> */
protected function toArray(Model $model): array
{
return $model->toArray();
}
/**
* Traduce `sort`/`order` del query string al formato del ORM.
*
* @param array<string, mixed> $query
* @return list<array{0: string, 1: 'ASC'|'DESC'}>
*/
private function orderFrom(array $query): array
{
$sort = (string) ($query['sort'] ?? '');
$order = strtoupper((string) ($query['order'] ?? 'ASC'));
if ($sort === '') {
return [];
}
return [[$sort, $order === 'DESC' ? 'DESC' : 'ASC']];
}
}
```
```php
<?php
declare(strict_types=1);
namespace App\Gateway;
final class ArticuloGateway extends OrmGateway {}
```
---
## 4. Manejo de duplicados
El ORM lanza `DuplicateKeyException`; la API responde 409. El mapeo vive en un controller, no en la
librería.
```php
<?php
declare(strict_types=1);
namespace App\Http;
use App\Gateway\ArticuloGateway;
use Camelia\Controllers\CrudController;
use Camelia\Controllers\Exception\Conflict;
use Camelia\Controllers\Request;
use Camelia\Controllers\Response;
use Camelia\Orm\Exception\DuplicateKeyException;
final class ArticuloController extends CrudController
{
public function __construct(ArticuloGateway $gateway)
{
parent::__construct($gateway, 'articulos');
}
public function store(Request $request): Response
{
try {
return parent::store($request);
} catch (DuplicateKeyException) {
return $this->error(new Conflict('An articulo with that code already exists.'));
}
}
}
```
---
## 5. Test de la API completa
```php
<?php
declare(strict_types=1);
namespace App\Tests;
use Camelia\Controllers\JsonRequest;
use Camelia\Controllers\ResourceGateway;
use Camelia\Controllers\Response;
use Camelia\Controllers\Router;
use Camelia\Controllers\Security\BearerAuth;
use PHPUnit\Framework\TestCase;
final class ApiTest extends TestCase
{
private function router(ResourceGateway $gateway, bool $authenticated = true): Router
{
$router = (new Router())->withMiddleware(
new BearerAuth(static fn (string $token): ?array => $authenticated ? ['id' => 1] : null),
);
$router->get('/articulos', new ArticuloController($gateway));
$router->get('/articulos/{id}', new ArticuloController($gateway));
$router->post('/articulos', new ArticuloController($gateway));
$router->delete('/articulos/{id}', new ArticuloController($gateway));
return $router;
}
public function testFullCrudFlow(): void
{
$gateway = new InMemoryGateway();
$router = $this->router($gateway);
// POST crea
$created = $router->dispatch(new JsonRequest(
method: 'POST',
path: '/articulos',
body: ['nombre' => 'Taladro', 'precio' => 120.5],
headers: ['authorization' => 'Bearer token'],
));
self::assertSame(201, $created->status());
self::assertSame('/articulos/1', $created->headers()['Location']);
self::assertSame('Taladro', $created->body()['nombre']);
// GET lo lee
$shown = $router->dispatch(new JsonRequest(
path: '/articulos/1',
headers: ['authorization' => 'Bearer token'],
));
self::assertSame(200, $shown->status());
self::assertSame(120.5, $shown->body()['precio']);
// GET lista
$listed = $router->dispatch(new JsonRequest(
path: '/articulos',
headers: ['authorization' => 'Bearer token'],
));
self::assertSame(1, $listed->body()['total']);
self::assertSame(20, $listed->body()['per_page']);
// DELETE borra
$deleted = $router->dispatch(new JsonRequest(
method: 'DELETE',
path: '/articulos/1',
headers: ['authorization' => 'Bearer token'],
));
self::assertSame(204, $deleted->status());
// Ya no existe
$missing = $router->dispatch(new JsonRequest(
path: '/articulos/1',
headers: ['authorization' => 'Bearer token'],
));
self::assertSame(404, $missing->status());
}
public function testRejectsAnonymous(): void
{
$router = $this->router(new InMemoryGateway(), authenticated: false);
$response = $router->dispatch(new JsonRequest(path: '/articulos'));
self::assertSame(401, $response->status());
self::assertSame('unauthorized', $response->body()['code']);
}
public function testPaginationClampsPerPage(): void
{
$gateway = new InMemoryGateway();
for ($i = 1; $i <= 30; ++$i) {
$gateway->create(['nombre' => 'Articulo ' . $i]);
}
$router = $this->router($gateway);
$response = $router->dispatch(new JsonRequest(
path: '/articulos',
query: ['page' => '2', 'per_page' => '10'],
headers: ['authorization' => 'Bearer token'],
));
self::assertSame(2, $response->body()['page']);
self::assertSame(10, $response->body()['per_page']);
self::assertSame(30, $response->body()['total']);
self::assertSame(3, $response->body()['total_pages']);
self::assertTrue($response->body()['has_next']);
self::assertTrue($response->body()['has_prev']);
}
}
final class InMemoryGateway implements ResourceGateway
{
/** @var array<int, array<string, mixed>> */
private array $records = [];
public function findAll(array $query = []): array
{
return array_values($this->records);
}
public function find(int|string $id): ?array
{
return $this->records[(int) $id] ?? null;
}
public function create(array $values): array
{
$id = count($this->records) + 1;
$this->records[$id] = ['id' => $id] + $values;
return $this->records[$id];
}
public function update(int|string $id, array $values): ?array
{
if (!isset($this->records[(int) $id])) {
return null;
}
return $this->records[(int) $id] = ['id' => (int) $id] + $values;
}
public function delete(int|string $id): bool
{
if (!isset($this->records[(int) $id])) {
return false;
}
unset($this->records[(int) $id]);
return true;
}
public function count(array $query = []): ?int
{
return count($this->records);
}
}
```
---
## 6. Recetas sueltas
### Rate limit por usuario autenticado, no por IP
```php
new RateLimit(
limit: 1000,
windowSeconds: 3600,
keyResolver: static function (Request $request): string {
$user = $request->attribute('user');
return is_array($user) ? 'user:' . (string) $user['id'] : 'anon';
},
);
```
Va **después** de `BearerAuth` en el pipeline; si va antes, todavía no hay identidad.
### CORS estricto para producción
```php
new Cors(
allowedOrigins: ['https://erp.midominio.com'],
allowedMethods: ['GET', 'POST', 'PUT', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization'],
allowCredentials: true,
maxAge: 3600,
);
```
### Un middleware que exige un header de trazabilidad
```php
final readonly class RequireTraceId implements Middleware
{
public function process(Request $request, callable $next): Response
{
$trace = $request->header('X-Trace-Id');
if ($trace === null || $trace === '') {
return new Response(
['error' => ['code' => 'bad_request', 'message' => 'X-Trace-Id is required.']],
400,
);
}
return $next($request)->withHeader('X-Trace-Id', $trace);
}
}
```
---
## Por dónde seguir
- **[GUIA-PROGRAMADOR.md](GUIA-PROGRAMADOR.md)** — el recorrido completo, con trampas.
- **[ARQUITECTURA.md](ARQUITECTURA.md)** — el porqué de cada pieza.