Add stage 3: todo list and item CRUD API

Two migrations add todo_lists (owner_id FK to users, title, description) and
todo_items (list_id FK, text, complete, position), both with ON DELETE
CASCADE.

New endpoints under /api/lists, all behind AuthMiddleware:
  - lists: index / store / show / update (PATCH) / destroy
  - items: nested under a list, same five verbs
Lists are owner-scoped — another user's or a missing list responds 404, never
403. New items append after the highest position unless one is given; the
list carries item_count / completed_count. Item PATCH is partial and never
renumbers siblings.

Adds App\Support\Validator for request-body checks, TodoList/TodoItem
repositories, and body()/user() helpers on the Controller base. Feature tests
move their shared harness into tests/ApiTestCase; TodoTest covers CRUD,
ownership isolation, ordering, completion counts, validation and cascade
delete. Full suite: 15 passing.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-09-03 18:30:52 +01:00
co-authored by Claude Sonnet 5
parent 5e3b8dbd7e
commit 5a0d29a308
12 changed files with 1093 additions and 4 deletions
+88
View File
@@ -0,0 +1,88 @@
<?php
declare(strict_types=1);
namespace Tests;
use PDO;
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\ResponseInterface;
use Slim\App;
use Slim\Psr7\Factory\ServerRequestFactory;
/**
* Boots the real Slim app against a throwaway SQLite database with all
* migrations applied.
*/
abstract class ApiTestCase extends TestCase
{
protected App $app;
private string $databasePath;
protected function setUp(): void
{
$this->databasePath = sys_get_temp_dir() . '/todo-test-' . uniqid() . '.sqlite';
putenv('DATABASE_PATH=' . $this->databasePath);
$_ENV['DATABASE_PATH'] = $this->databasePath;
$pdo = new PDO('sqlite:' . $this->databasePath);
$pdo->exec('PRAGMA foreign_keys = ON');
foreach (glob(dirname(__DIR__) . '/migrations/*.sql') ?: [] as $migration) {
$pdo->exec((string) file_get_contents($migration));
}
$this->app = require dirname(__DIR__) . '/src/bootstrap.php';
}
protected function tearDown(): void
{
@unlink($this->databasePath);
putenv('DATABASE_PATH');
unset($_ENV['DATABASE_PATH']);
}
/**
* @param array<string, mixed>|null $body
* @param array<string, string> $headers
*/
protected function request(
string $method,
string $path,
?array $body = null,
array $headers = [],
): ResponseInterface {
$request = (new ServerRequestFactory())->createServerRequest($method, $path);
foreach ($headers as $name => $value) {
$request = $request->withHeader($name, $value);
}
if ($body !== null) {
$request = $request->withParsedBody($body)->withHeader('Content-Type', 'application/json');
}
return $this->app->handle($request);
}
/**
* Register a fresh user and return an `Authorization` header for them.
*
* @return array<string, string>
*/
protected function authHeader(string $email = 'user@example.com'): array
{
$token = $this->decode(
$this->request('POST', '/api/auth/register', ['email' => $email, 'password' => 'password123']),
)['token'];
return ['Authorization' => 'Bearer ' . $token];
}
/**
* @return array<string, mixed>
*/
protected function decode(ResponseInterface $response): array
{
return (array) json_decode((string) $response->getBody(), true, 512, JSON_THROW_ON_ERROR);
}
}
+153
View File
@@ -0,0 +1,153 @@
<?php
declare(strict_types=1);
namespace Tests;
final class TodoTest extends ApiTestCase
{
public function test_lists_require_authentication(): void
{
self::assertSame(401, $this->request('GET', '/api/lists')->getStatusCode());
}
public function test_create_and_list_lists(): void
{
$auth = $this->authHeader();
$created = $this->request('POST', '/api/lists', [
'title' => ' Groceries ',
'description' => 'Weekly shop',
], $auth);
self::assertSame(201, $created->getStatusCode());
$list = $this->decode($created)['list'];
self::assertSame('Groceries', $list['title']);
self::assertSame('Weekly shop', $list['description']);
self::assertSame(0, $list['item_count']);
$index = $this->decode($this->request('GET', '/api/lists', null, $auth));
self::assertCount(1, $index['lists']);
self::assertSame($list['id'], $index['lists'][0]['id']);
}
public function test_list_creation_validates_title(): void
{
$response = $this->request('POST', '/api/lists', ['description' => 'no title'], $this->authHeader());
self::assertSame(422, $response->getStatusCode());
self::assertArrayHasKey('title', $this->decode($response)['error']['details']);
}
public function test_a_list_is_only_visible_to_its_owner(): void
{
$owner = $this->authHeader('owner@example.com');
$other = $this->authHeader('other@example.com');
$listId = $this->decode(
$this->request('POST', '/api/lists', ['title' => 'Private'], $owner),
)['list']['id'];
self::assertSame(200, $this->request('GET', "/api/lists/{$listId}", null, $owner)->getStatusCode());
self::assertSame(404, $this->request('GET', "/api/lists/{$listId}", null, $other)->getStatusCode());
self::assertSame(404, $this->request('PATCH', "/api/lists/{$listId}", ['title' => 'x'], $other)->getStatusCode());
self::assertSame(404, $this->request('DELETE', "/api/lists/{$listId}", null, $other)->getStatusCode());
}
public function test_update_and_delete_list(): void
{
$auth = $this->authHeader();
$listId = $this->decode(
$this->request('POST', '/api/lists', ['title' => 'Draft'], $auth),
)['list']['id'];
$updated = $this->decode(
$this->request('PATCH', "/api/lists/{$listId}", ['title' => 'Final'], $auth),
)['list'];
self::assertSame('Final', $updated['title']);
self::assertSame(204, $this->request('DELETE', "/api/lists/{$listId}", null, $auth)->getStatusCode());
self::assertSame(404, $this->request('GET', "/api/lists/{$listId}", null, $auth)->getStatusCode());
}
public function test_items_append_in_order_and_track_completion(): void
{
$auth = $this->authHeader();
$listId = $this->decode(
$this->request('POST', '/api/lists', ['title' => 'Chores'], $auth),
)['list']['id'];
foreach (['Wash up', 'Hoover', 'Bins'] as $text) {
$this->request('POST', "/api/lists/{$listId}/items", ['text' => $text], $auth);
}
$items = $this->decode($this->request('GET', "/api/lists/{$listId}/items", null, $auth))['items'];
self::assertSame(['Wash up', 'Hoover', 'Bins'], array_column($items, 'text'));
self::assertSame([0, 1, 2], array_column($items, 'position'));
self::assertFalse($items[0]['complete']);
$done = $this->decode(
$this->request('PATCH', "/api/lists/{$listId}/items/{$items[0]['id']}", ['complete' => true], $auth),
)['item'];
self::assertTrue($done['complete']);
$list = $this->decode($this->request('GET', "/api/lists/{$listId}", null, $auth))['list'];
self::assertSame(3, $list['item_count']);
self::assertSame(1, $list['completed_count']);
}
public function test_item_creation_accepts_explicit_position_and_validates_text(): void
{
$auth = $this->authHeader();
$listId = $this->decode(
$this->request('POST', '/api/lists', ['title' => 'L'], $auth),
)['list']['id'];
$item = $this->decode(
$this->request('POST', "/api/lists/{$listId}/items", ['text' => 'Pinned', 'position' => 5], $auth),
)['item'];
self::assertSame(5, $item['position']);
$bad = $this->request('POST', "/api/lists/{$listId}/items", ['text' => ' '], $auth);
self::assertSame(422, $bad->getStatusCode());
self::assertArrayHasKey('text', $this->decode($bad)['error']['details']);
}
public function test_deleting_a_list_cascades_to_its_items(): void
{
$auth = $this->authHeader();
$listId = $this->decode(
$this->request('POST', '/api/lists', ['title' => 'Temp'], $auth),
)['list']['id'];
$itemId = $this->decode(
$this->request('POST', "/api/lists/{$listId}/items", ['text' => 'x'], $auth),
)['item']['id'];
$this->request('DELETE', "/api/lists/{$listId}", null, $auth);
// The parent list is gone, so the item route 404s on the list check.
self::assertSame(
404,
$this->request('GET', "/api/lists/{$listId}/items/{$itemId}", null, $auth)->getStatusCode(),
);
}
public function test_items_under_another_users_list_are_not_reachable(): void
{
$owner = $this->authHeader('owner2@example.com');
$other = $this->authHeader('other2@example.com');
$listId = $this->decode(
$this->request('POST', '/api/lists', ['title' => 'Mine'], $owner),
)['list']['id'];
self::assertSame(
404,
$this->request('POST', "/api/lists/{$listId}/items", ['text' => 'sneaky'], $other)->getStatusCode(),
);
self::assertSame(
404,
$this->request('GET', "/api/lists/{$listId}/items", null, $other)->getStatusCode(),
);
}
}