# 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 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_` 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 $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 */ protected function toArray(Model $model): array { return $model->toArray(); } /** * Traduce `sort`/`order` del query string al formato del ORM. * * @param array $query * @return list */ 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 error(new Conflict('An articulo with that code already exists.')); } } } ``` --- ## 5. Test de la API completa ```php 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> */ 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.