Rename lists -> projects and items -> cards throughout

Project scope shifts from a todo list to a project-management app. This is a
straight terminology rename across code, comments, migrations, tests, and
docs — no behaviour change.

- DB: table todo_lists -> projects, todo_items -> cards, column
  todo_items.list_id -> cards.project_id, indexes renamed. Migrations 003/004
  rewritten in place (destructive; recreate the volume with `down -v`).
- API: /api/lists -> /api/projects, nested /items -> /cards, reorder body
  item_ids -> card_ids, JSON keys list/lists/item/items -> project/projects/
  card/cards, item_count -> card_count, list_id -> project_id, and the
  matching error messages.
- PHP: TodoList/TodoItem Repository + Controller -> Project/Card; shared SQL
  aliases l/i -> p/c.
- Frontend: stores lists.ts/items.ts -> projects.ts/cards.ts (useProjectsStore
  / useCardsStore, MAX_PROJECTS), ListView -> ProjectView, TodoItemRow ->
  CardRow, route /lists/:id -> /projects/:id (name "project"), types TodoList/
  TodoItem -> Project/Card, and all UI copy. CSS .lists*/.list-head* ->
  .projects*/.project-head*, .item* -> .card-row* (kept the generic .card
  panel class), .items -> .cards.
- Product name in the header, PWA manifest, index.html title and package
  descriptions -> "Project Manager" / "Projects".

Backend suite: 37 passing.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-09-04 11:28:59 +01:00
co-authored by Claude Sonnet 5
parent be592f38fc
commit c66e5ceb9b
30 changed files with 1068 additions and 1065 deletions
+187
View File
@@ -0,0 +1,187 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Exception\ApiException;
use App\Repository\CardRepository;
use App\Repository\ProjectRepository;
use App\Support\Validator;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
/**
* CRUD for the cards within one project. Every route first checks that the
* parent project is owned by the authenticated user; otherwise it responds 404.
*/
final class CardController extends Controller
{
private const TEXT_MAX = 1000;
public function __construct(
private readonly ProjectRepository $projects,
private readonly CardRepository $cards,
) {
}
/**
* GET /api/projects/{projectId}/cards
*/
public function index(Request $request, Response $response, array $args): Response
{
$projectId = $this->requireOwnedProjectId($request, $args);
return $this->json($response, [
'cards' => array_map($this->present(...), $this->cards->allForProject($projectId)),
]);
}
/**
* POST /api/projects/{projectId}/cards
*/
public function store(Request $request, Response $response, array $args): Response
{
$projectId = $this->requireOwnedProjectId($request, $args);
$validator = new Validator($this->body($request));
$text = $validator->requiredString('text', self::TEXT_MAX);
$complete = $validator->optionalBool('complete') ?? false;
$position = $validator->optionalInt('position', 0);
$validator->assert();
$card = $this->cards->create($projectId, $text, $complete, $position);
$this->projects->touch($projectId);
return $this->json($response, ['card' => $this->present($card)], 201);
}
/**
* GET /api/projects/{projectId}/cards/{cardId}
*/
public function show(Request $request, Response $response, array $args): Response
{
$projectId = $this->requireOwnedProjectId($request, $args);
return $this->json($response, ['card' => $this->present($this->requireCard($projectId, $args))]);
}
/**
* PATCH /api/projects/{projectId}/cards/{cardId}
*/
public function update(Request $request, Response $response, array $args): Response
{
$projectId = $this->requireOwnedProjectId($request, $args);
$card = $this->requireCard($projectId, $args);
$validator = new Validator($this->body($request));
$fields = [];
if ($validator->has('text')) {
$fields['text'] = $validator->requiredString('text', self::TEXT_MAX);
}
if ($validator->has('complete')) {
$fields['complete'] = $validator->optionalBool('complete');
}
if ($validator->has('position')) {
$fields['position'] = $validator->optionalInt('position', 0);
}
if ($fields === [] && !$validator->failed()) {
$validator->add('text', 'Provide at least one of: text, complete, position.');
}
$validator->assert();
$updated = $this->cards->update($card['id'], $projectId, $fields);
$this->projects->touch($projectId);
return $this->json($response, ['card' => $this->present($updated)]);
}
/**
* DELETE /api/projects/{projectId}/cards/{cardId}
*/
public function destroy(Request $request, Response $response, array $args): Response
{
$projectId = $this->requireOwnedProjectId($request, $args);
$this->cards->delete($this->requireCard($projectId, $args)['id']);
$this->projects->touch($projectId);
return $response->withStatus(204);
}
/**
* PUT /api/projects/{projectId}/cards/order
*
* Body: { "card_ids": [3, 1, 2] } — every card in the project, exactly once,
* in the desired order. Positions are rewritten to 0..n-1.
*/
public function reorder(Request $request, Response $response, array $args): Response
{
$projectId = $this->requireOwnedProjectId($request, $args);
$order = $this->body($request)['card_ids'] ?? null;
if (!is_array($order) || array_filter($order, static fn ($id) => !is_int($id)) !== []) {
throw new ApiException('card_ids must be an array of card IDs.', 422);
}
/** @var int[] $order */
$expected = $this->cards->idsForProject($projectId);
$given = $order;
sort($given);
sort($expected);
if ($given !== $expected) {
throw new ApiException('card_ids must contain every card in the project exactly once.', 422);
}
$cards = $this->cards->reorder($projectId, $order);
$this->projects->touch($projectId);
return $this->json($response, ['cards' => array_map($this->present(...), $cards)]);
}
/**
* @param array<string, string> $args
*/
private function requireOwnedProjectId(Request $request, array $args): int
{
$project = $this->projects->findOwnedBy((int) $args['projectId'], $this->user($request)['id']);
if ($project === null) {
throw new ApiException('Project not found.', 404);
}
return $project['id'];
}
/**
* @param array<string, string> $args
* @return array{id: int, project_id: int, text: string, complete: bool, position: int, created_at: string, updated_at: string}
*/
private function requireCard(int $projectId, array $args): array
{
$card = $this->cards->findInProject((int) $args['cardId'], $projectId);
if ($card === null) {
throw new ApiException('Card not found.', 404);
}
return $card;
}
/**
* @param array{id: int, project_id: int, text: string, complete: bool, position: int, created_at: string, updated_at: string} $card
* @return array<string, mixed>
*/
private function present(array $card): array
{
return [
'id' => $card['id'],
'project_id' => $card['project_id'],
'text' => $card['text'],
'complete' => $card['complete'],
'position' => $card['position'],
'created_at' => $card['created_at'],
'updated_at' => $card['updated_at'],
];
}
}
+139
View File
@@ -0,0 +1,139 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Exception\ApiException;
use App\Repository\ProjectRepository;
use App\Support\Validator;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
/**
* CRUD for the authenticated user's projects. A project is only ever visible to
* its owner; anything else responds 404.
*/
final class ProjectController extends Controller
{
private const TITLE_MAX = 255;
private const DESCRIPTION_MAX = 2000;
private const MAX_PROJECTS_PER_OWNER = 100;
public function __construct(private readonly ProjectRepository $projects)
{
}
/**
* GET /api/projects
*/
public function index(Request $request, Response $response): Response
{
$projects = $this->projects->allForOwner($this->user($request)['id']);
return $this->json($response, ['projects' => array_map($this->present(...), $projects)]);
}
/**
* POST /api/projects
*/
public function store(Request $request, Response $response): Response
{
$ownerId = $this->user($request)['id'];
$validator = new Validator($this->body($request));
$title = $validator->requiredString('title', self::TITLE_MAX);
$description = $validator->optionalString('description', self::DESCRIPTION_MAX) ?? '';
$validator->assert();
if ($this->projects->countForOwner($ownerId) >= self::MAX_PROJECTS_PER_OWNER) {
throw new ApiException(
sprintf('You have reached the maximum of %d projects.', self::MAX_PROJECTS_PER_OWNER),
409,
);
}
$project = $this->projects->create($ownerId, $title, $description);
return $this->json($response, ['project' => $this->present($project)], 201);
}
/**
* GET /api/projects/{projectId}
*/
public function show(Request $request, Response $response, array $args): Response
{
return $this->json($response, ['project' => $this->present($this->requireOwnedProject($request, $args))]);
}
/**
* PATCH /api/projects/{projectId}
*/
public function update(Request $request, Response $response, array $args): Response
{
$project = $this->requireOwnedProject($request, $args);
$validator = new Validator($this->body($request));
$fields = [];
if ($validator->has('title')) {
$fields['title'] = $validator->requiredString('title', self::TITLE_MAX);
}
if ($validator->has('description')) {
$fields['description'] = $validator->optionalString('description', self::DESCRIPTION_MAX) ?? '';
}
if ($fields === [] && !$validator->failed()) {
$validator->add('title', 'Provide at least one of: title, description.');
}
$validator->assert();
$updated = $this->projects->update($project['id'], $project['owner_id'], $fields);
return $this->json($response, ['project' => $this->present($updated)]);
}
/**
* DELETE /api/projects/{projectId}
*/
public function destroy(Request $request, Response $response, array $args): Response
{
$this->projects->delete($this->requireOwnedProject($request, $args)['id']);
return $response->withStatus(204);
}
/**
* Load the project named in the route, or 404 if it is missing or not owned
* by the authenticated user.
*
* @param array<string, string> $args
* @return array{id: int, owner_id: int, title: string, description: string, card_count: int, completed_count: int, created_at: string, updated_at: string}
*/
private function requireOwnedProject(Request $request, array $args): array
{
$project = $this->projects->findOwnedBy((int) $args['projectId'], $this->user($request)['id']);
if ($project === null) {
throw new ApiException('Project not found.', 404);
}
return $project;
}
/**
* @param array{id: int, owner_id: int, title: string, description: string, card_count: int, completed_count: int, created_at: string, updated_at: string} $project
* @return array<string, mixed>
*/
private function present(array $project): array
{
return [
'id' => $project['id'],
'title' => $project['title'],
'description' => $project['description'],
'owner_id' => $project['owner_id'],
'card_count' => $project['card_count'],
'completed_count' => $project['completed_count'],
'created_at' => $project['created_at'],
'updated_at' => $project['updated_at'],
];
}
}
-187
View File
@@ -1,187 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Exception\ApiException;
use App\Repository\TodoItemRepository;
use App\Repository\TodoListRepository;
use App\Support\Validator;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
/**
* CRUD for the items within one todo list. Every route first checks that the
* parent list is owned by the authenticated user; otherwise it responds 404.
*/
final class TodoItemController extends Controller
{
private const TEXT_MAX = 1000;
public function __construct(
private readonly TodoListRepository $lists,
private readonly TodoItemRepository $items,
) {
}
/**
* GET /api/lists/{listId}/items
*/
public function index(Request $request, Response $response, array $args): Response
{
$listId = $this->requireOwnedListId($request, $args);
return $this->json($response, [
'items' => array_map($this->present(...), $this->items->allForList($listId)),
]);
}
/**
* POST /api/lists/{listId}/items
*/
public function store(Request $request, Response $response, array $args): Response
{
$listId = $this->requireOwnedListId($request, $args);
$validator = new Validator($this->body($request));
$text = $validator->requiredString('text', self::TEXT_MAX);
$complete = $validator->optionalBool('complete') ?? false;
$position = $validator->optionalInt('position', 0);
$validator->assert();
$item = $this->items->create($listId, $text, $complete, $position);
$this->lists->touch($listId);
return $this->json($response, ['item' => $this->present($item)], 201);
}
/**
* GET /api/lists/{listId}/items/{itemId}
*/
public function show(Request $request, Response $response, array $args): Response
{
$listId = $this->requireOwnedListId($request, $args);
return $this->json($response, ['item' => $this->present($this->requireItem($listId, $args))]);
}
/**
* PATCH /api/lists/{listId}/items/{itemId}
*/
public function update(Request $request, Response $response, array $args): Response
{
$listId = $this->requireOwnedListId($request, $args);
$item = $this->requireItem($listId, $args);
$validator = new Validator($this->body($request));
$fields = [];
if ($validator->has('text')) {
$fields['text'] = $validator->requiredString('text', self::TEXT_MAX);
}
if ($validator->has('complete')) {
$fields['complete'] = $validator->optionalBool('complete');
}
if ($validator->has('position')) {
$fields['position'] = $validator->optionalInt('position', 0);
}
if ($fields === [] && !$validator->failed()) {
$validator->add('text', 'Provide at least one of: text, complete, position.');
}
$validator->assert();
$updated = $this->items->update($item['id'], $listId, $fields);
$this->lists->touch($listId);
return $this->json($response, ['item' => $this->present($updated)]);
}
/**
* DELETE /api/lists/{listId}/items/{itemId}
*/
public function destroy(Request $request, Response $response, array $args): Response
{
$listId = $this->requireOwnedListId($request, $args);
$this->items->delete($this->requireItem($listId, $args)['id']);
$this->lists->touch($listId);
return $response->withStatus(204);
}
/**
* PUT /api/lists/{listId}/items/order
*
* Body: { "item_ids": [3, 1, 2] } — every item in the list, exactly once,
* in the desired order. Positions are rewritten to 0..n-1.
*/
public function reorder(Request $request, Response $response, array $args): Response
{
$listId = $this->requireOwnedListId($request, $args);
$order = $this->body($request)['item_ids'] ?? null;
if (!is_array($order) || array_filter($order, static fn ($id) => !is_int($id)) !== []) {
throw new ApiException('item_ids must be an array of item IDs.', 422);
}
/** @var int[] $order */
$expected = $this->items->idsForList($listId);
$given = $order;
sort($given);
sort($expected);
if ($given !== $expected) {
throw new ApiException('item_ids must contain every item in the list exactly once.', 422);
}
$items = $this->items->reorder($listId, $order);
$this->lists->touch($listId);
return $this->json($response, ['items' => array_map($this->present(...), $items)]);
}
/**
* @param array<string, string> $args
*/
private function requireOwnedListId(Request $request, array $args): int
{
$list = $this->lists->findOwnedBy((int) $args['listId'], $this->user($request)['id']);
if ($list === null) {
throw new ApiException('List not found.', 404);
}
return $list['id'];
}
/**
* @param array<string, string> $args
* @return array{id: int, list_id: int, text: string, complete: bool, position: int, created_at: string, updated_at: string}
*/
private function requireItem(int $listId, array $args): array
{
$item = $this->items->findInList((int) $args['itemId'], $listId);
if ($item === null) {
throw new ApiException('Item not found.', 404);
}
return $item;
}
/**
* @param array{id: int, list_id: int, text: string, complete: bool, position: int, created_at: string, updated_at: string} $item
* @return array<string, mixed>
*/
private function present(array $item): array
{
return [
'id' => $item['id'],
'list_id' => $item['list_id'],
'text' => $item['text'],
'complete' => $item['complete'],
'position' => $item['position'],
'created_at' => $item['created_at'],
'updated_at' => $item['updated_at'],
];
}
}
-139
View File
@@ -1,139 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Exception\ApiException;
use App\Repository\TodoListRepository;
use App\Support\Validator;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
/**
* CRUD for the authenticated user's todo lists. A list is only ever visible to
* its owner; anything else responds 404.
*/
final class TodoListController extends Controller
{
private const TITLE_MAX = 255;
private const DESCRIPTION_MAX = 2000;
private const MAX_LISTS_PER_OWNER = 100;
public function __construct(private readonly TodoListRepository $lists)
{
}
/**
* GET /api/lists
*/
public function index(Request $request, Response $response): Response
{
$lists = $this->lists->allForOwner($this->user($request)['id']);
return $this->json($response, ['lists' => array_map($this->present(...), $lists)]);
}
/**
* POST /api/lists
*/
public function store(Request $request, Response $response): Response
{
$ownerId = $this->user($request)['id'];
$validator = new Validator($this->body($request));
$title = $validator->requiredString('title', self::TITLE_MAX);
$description = $validator->optionalString('description', self::DESCRIPTION_MAX) ?? '';
$validator->assert();
if ($this->lists->countForOwner($ownerId) >= self::MAX_LISTS_PER_OWNER) {
throw new ApiException(
sprintf('You have reached the maximum of %d lists.', self::MAX_LISTS_PER_OWNER),
409,
);
}
$list = $this->lists->create($ownerId, $title, $description);
return $this->json($response, ['list' => $this->present($list)], 201);
}
/**
* GET /api/lists/{listId}
*/
public function show(Request $request, Response $response, array $args): Response
{
return $this->json($response, ['list' => $this->present($this->requireOwnedList($request, $args))]);
}
/**
* PATCH /api/lists/{listId}
*/
public function update(Request $request, Response $response, array $args): Response
{
$list = $this->requireOwnedList($request, $args);
$validator = new Validator($this->body($request));
$fields = [];
if ($validator->has('title')) {
$fields['title'] = $validator->requiredString('title', self::TITLE_MAX);
}
if ($validator->has('description')) {
$fields['description'] = $validator->optionalString('description', self::DESCRIPTION_MAX) ?? '';
}
if ($fields === [] && !$validator->failed()) {
$validator->add('title', 'Provide at least one of: title, description.');
}
$validator->assert();
$updated = $this->lists->update($list['id'], $list['owner_id'], $fields);
return $this->json($response, ['list' => $this->present($updated)]);
}
/**
* DELETE /api/lists/{listId}
*/
public function destroy(Request $request, Response $response, array $args): Response
{
$this->lists->delete($this->requireOwnedList($request, $args)['id']);
return $response->withStatus(204);
}
/**
* Load the list named in the route, or 404 if it is missing or not owned by
* the authenticated user.
*
* @param array<string, string> $args
* @return array{id: int, owner_id: int, title: string, description: string, item_count: int, completed_count: int, created_at: string, updated_at: string}
*/
private function requireOwnedList(Request $request, array $args): array
{
$list = $this->lists->findOwnedBy((int) $args['listId'], $this->user($request)['id']);
if ($list === null) {
throw new ApiException('List not found.', 404);
}
return $list;
}
/**
* @param array{id: int, owner_id: int, title: string, description: string, item_count: int, completed_count: int, created_at: string, updated_at: string} $list
* @return array<string, mixed>
*/
private function present(array $list): array
{
return [
'id' => $list['id'],
'title' => $list['title'],
'description' => $list['description'],
'owner_id' => $list['owner_id'],
'item_count' => $list['item_count'],
'completed_count' => $list['completed_count'],
'created_at' => $list['created_at'],
'updated_at' => $list['updated_at'],
];
}
}
@@ -7,39 +7,39 @@ namespace App\Repository;
use PDO;
/**
* Data access for the `todo_items` table.
* Data access for the `cards` table.
*
* @phpstan-type TodoItemRow array{
* id: int, list_id: int, text: string, complete: bool, position: int,
* @phpstan-type CardRow array{
* id: int, project_id: int, text: string, complete: bool, position: int,
* created_at: string, updated_at: string
* }
*/
final class TodoItemRepository
final class CardRepository
{
public function __construct(private readonly PDO $pdo)
{
}
/**
* @return TodoItemRow[]
* @return CardRow[]
*/
public function allForList(int $listId): array
public function allForProject(int $projectId): array
{
$stmt = $this->pdo->prepare(
'SELECT * FROM todo_items WHERE list_id = :list ORDER BY position ASC, id ASC'
'SELECT * FROM cards WHERE project_id = :project ORDER BY position ASC, id ASC'
);
$stmt->execute(['list' => $listId]);
$stmt->execute(['project' => $projectId]);
return array_map($this->cast(...), $stmt->fetchAll());
}
/**
* @return TodoItemRow|null
* @return CardRow|null
*/
public function findInList(int $id, int $listId): ?array
public function findInProject(int $id, int $projectId): ?array
{
$stmt = $this->pdo->prepare('SELECT * FROM todo_items WHERE id = :id AND list_id = :list');
$stmt->execute(['id' => $id, 'list' => $listId]);
$stmt = $this->pdo->prepare('SELECT * FROM cards WHERE id = :id AND project_id = :project');
$stmt->execute(['id' => $id, 'project' => $projectId]);
$row = $stmt->fetch();
@@ -47,34 +47,34 @@ final class TodoItemRepository
}
/**
* @return TodoItemRow
* @return CardRow
*/
public function create(int $listId, string $text, bool $complete, ?int $position): array
public function create(int $projectId, string $text, bool $complete, ?int $position): array
{
$position ??= $this->nextPosition($listId);
$position ??= $this->nextPosition($projectId);
$stmt = $this->pdo->prepare(
'INSERT INTO todo_items (list_id, text, complete, position)
VALUES (:list, :text, :complete, :position)'
'INSERT INTO cards (project_id, text, complete, position)
VALUES (:project, :text, :complete, :position)'
);
$stmt->execute([
'list' => $listId,
'project' => $projectId,
'text' => $text,
'complete' => $complete ? 1 : 0,
'position' => $position,
]);
/** @var TodoItemRow $item */
$item = $this->findInList((int) $this->pdo->lastInsertId(), $listId);
/** @var CardRow $card */
$card = $this->findInProject((int) $this->pdo->lastInsertId(), $projectId);
return $item;
return $card;
}
/**
* @param array{text?: string, complete?: bool, position?: int} $fields
* @return TodoItemRow
* @return CardRow
*/
public function update(int $id, int $listId, array $fields): array
public function update(int $id, int $projectId, array $fields): array
{
$sets = ['updated_at = ' . "strftime('%Y-%m-%dT%H:%M:%SZ', 'now')"];
$params = ['id' => $id];
@@ -92,53 +92,53 @@ final class TodoItemRepository
$params['position'] = $fields['position'];
}
$stmt = $this->pdo->prepare('UPDATE todo_items SET ' . implode(', ', $sets) . ' WHERE id = :id');
$stmt = $this->pdo->prepare('UPDATE cards SET ' . implode(', ', $sets) . ' WHERE id = :id');
$stmt->execute($params);
/** @var TodoItemRow $item */
$item = $this->findInList($id, $listId);
/** @var CardRow $card */
$card = $this->findInProject($id, $projectId);
return $item;
return $card;
}
public function delete(int $id): void
{
$this->pdo->prepare('DELETE FROM todo_items WHERE id = :id')->execute(['id' => $id]);
$this->pdo->prepare('DELETE FROM cards WHERE id = :id')->execute(['id' => $id]);
}
/**
* IDs of every item in the list, in current position order.
* IDs of every card in the project, in current position order.
*
* @return int[]
*/
public function idsForList(int $listId): array
public function idsForProject(int $projectId): array
{
$stmt = $this->pdo->prepare(
'SELECT id FROM todo_items WHERE list_id = :list ORDER BY position ASC, id ASC'
'SELECT id FROM cards WHERE project_id = :project ORDER BY position ASC, id ASC'
);
$stmt->execute(['list' => $listId]);
$stmt->execute(['project' => $projectId]);
return array_map(intval(...), $stmt->fetchAll(PDO::FETCH_COLUMN));
}
/**
* Assign positions 0..n-1 to the given items in one transaction.
* Assign positions 0..n-1 to the given cards in one transaction.
*
* @param int[] $orderedIds every item id in the list, exactly once
* @return TodoItemRow[] the list's items in their new order
* @param int[] $orderedIds every card id in the project, exactly once
* @return CardRow[] the project's cards in their new order
*/
public function reorder(int $listId, array $orderedIds): array
public function reorder(int $projectId, array $orderedIds): array
{
$stmt = $this->pdo->prepare(
'UPDATE todo_items SET position = :position,
'UPDATE cards SET position = :position,
updated_at = ' . "strftime('%Y-%m-%dT%H:%M:%SZ', 'now')" . '
WHERE id = :id AND list_id = :list'
WHERE id = :id AND project_id = :project'
);
$this->pdo->beginTransaction();
try {
foreach (array_values($orderedIds) as $position => $id) {
$stmt->execute(['position' => $position, 'id' => $id, 'list' => $listId]);
$stmt->execute(['position' => $position, 'id' => $id, 'project' => $projectId]);
}
$this->pdo->commit();
} catch (\Throwable $e) {
@@ -146,31 +146,31 @@ final class TodoItemRepository
throw $e;
}
return $this->allForList($listId);
return $this->allForProject($projectId);
}
private function nextPosition(int $listId): int
private function nextPosition(int $projectId): int
{
$stmt = $this->pdo->prepare(
'SELECT COALESCE(MAX(position), -1) + 1 FROM todo_items WHERE list_id = :list'
'SELECT COALESCE(MAX(position), -1) + 1 FROM cards WHERE project_id = :project'
);
$stmt->execute(['list' => $listId]);
$stmt->execute(['project' => $projectId]);
return (int) $stmt->fetchColumn();
}
/**
* @param array<string, mixed> $row
* @return TodoItemRow
* @return CardRow
*/
private function cast(array $row): array
{
$row['id'] = (int) $row['id'];
$row['list_id'] = (int) $row['list_id'];
$row['project_id'] = (int) $row['project_id'];
$row['complete'] = (bool) $row['complete'];
$row['position'] = (int) $row['position'];
/** @var TodoItemRow $row */
/** @var CardRow $row */
return $row;
}
}
@@ -7,20 +7,20 @@ namespace App\Repository;
use PDO;
/**
* Data access for the `todo_lists` table.
* Data access for the `projects` table.
*
* @phpstan-type TodoListRow array{
* @phpstan-type ProjectRow array{
* id: int, owner_id: int, title: string, description: string,
* item_count: int, completed_count: int, created_at: string, updated_at: string
* card_count: int, completed_count: int, created_at: string, updated_at: string
* }
*/
final class TodoListRepository
final class ProjectRepository
{
private const SELECT = <<<'SQL'
SELECT l.id, l.owner_id, l.title, l.description, l.created_at, l.updated_at,
(SELECT COUNT(*) FROM todo_items i WHERE i.list_id = l.id) AS item_count,
(SELECT COUNT(*) FROM todo_items i WHERE i.list_id = l.id AND i.complete = 1) AS completed_count
FROM todo_lists l
SELECT p.id, p.owner_id, p.title, p.description, p.created_at, p.updated_at,
(SELECT COUNT(*) FROM cards c WHERE c.project_id = p.id) AS card_count,
(SELECT COUNT(*) FROM cards c WHERE c.project_id = p.id AND c.complete = 1) AS completed_count
FROM projects p
SQL;
public function __construct(private readonly PDO $pdo)
@@ -28,15 +28,15 @@ final class TodoListRepository
}
/**
* Every list owned by the user, always sorted alphabetically by title
* Every project owned by the user, always sorted alphabetically by title
* (case-insensitive). There is deliberately no other ordering option.
*
* @return TodoListRow[]
* @return ProjectRow[]
*/
public function allForOwner(int $ownerId): array
{
$stmt = $this->pdo->prepare(
self::SELECT . ' WHERE l.owner_id = :owner ORDER BY l.title COLLATE NOCASE ASC, l.id ASC'
self::SELECT . ' WHERE p.owner_id = :owner ORDER BY p.title COLLATE NOCASE ASC, p.id ASC'
);
$stmt->execute(['owner' => $ownerId]);
@@ -45,18 +45,18 @@ final class TodoListRepository
public function countForOwner(int $ownerId): int
{
$stmt = $this->pdo->prepare('SELECT COUNT(*) FROM todo_lists WHERE owner_id = :owner');
$stmt = $this->pdo->prepare('SELECT COUNT(*) FROM projects WHERE owner_id = :owner');
$stmt->execute(['owner' => $ownerId]);
return (int) $stmt->fetchColumn();
}
/**
* @return TodoListRow|null
* @return ProjectRow|null
*/
public function findOwnedBy(int $id, int $ownerId): ?array
{
$stmt = $this->pdo->prepare(self::SELECT . ' WHERE l.id = :id AND l.owner_id = :owner');
$stmt = $this->pdo->prepare(self::SELECT . ' WHERE p.id = :id AND p.owner_id = :owner');
$stmt->execute(['id' => $id, 'owner' => $ownerId]);
$row = $stmt->fetch();
@@ -65,12 +65,12 @@ final class TodoListRepository
}
/**
* @return TodoListRow
* @return ProjectRow
*/
public function create(int $ownerId, string $title, string $description): array
{
$stmt = $this->pdo->prepare(
'INSERT INTO todo_lists (owner_id, title, description) VALUES (:owner, :title, :description)'
'INSERT INTO projects (owner_id, title, description) VALUES (:owner, :title, :description)'
);
$stmt->execute([
'owner' => $ownerId,
@@ -78,15 +78,15 @@ final class TodoListRepository
'description' => $description,
]);
/** @var TodoListRow $list */
$list = $this->findOwnedBy((int) $this->pdo->lastInsertId(), $ownerId);
/** @var ProjectRow $project */
$project = $this->findOwnedBy((int) $this->pdo->lastInsertId(), $ownerId);
return $list;
return $project;
}
/**
* @param array{title?: string, description?: string} $fields
* @return TodoListRow
* @return ProjectRow
*/
public function update(int $id, int $ownerId, array $fields): array
{
@@ -100,24 +100,24 @@ final class TodoListRepository
}
}
$stmt = $this->pdo->prepare('UPDATE todo_lists SET ' . implode(', ', $sets) . ' WHERE id = :id');
$stmt = $this->pdo->prepare('UPDATE projects SET ' . implode(', ', $sets) . ' WHERE id = :id');
$stmt->execute($params);
/** @var TodoListRow $list */
$list = $this->findOwnedBy($id, $ownerId);
/** @var ProjectRow $project */
$project = $this->findOwnedBy($id, $ownerId);
return $list;
return $project;
}
public function delete(int $id): void
{
$this->pdo->prepare('DELETE FROM todo_lists WHERE id = :id')->execute(['id' => $id]);
$this->pdo->prepare('DELETE FROM projects WHERE id = :id')->execute(['id' => $id]);
}
/** Bump updated_at, e.g. when the list's items change. */
/** Bump updated_at, e.g. when the project's cards change. */
public function touch(int $id): void
{
$this->pdo->prepare('UPDATE todo_lists SET updated_at = ' . $this->nowExpr() . ' WHERE id = :id')
$this->pdo->prepare('UPDATE projects SET updated_at = ' . $this->nowExpr() . ' WHERE id = :id')
->execute(['id' => $id]);
}
@@ -128,16 +128,16 @@ final class TodoListRepository
/**
* @param array<string, mixed> $row
* @return TodoListRow
* @return ProjectRow
*/
private function cast(array $row): array
{
$row['id'] = (int) $row['id'];
$row['owner_id'] = (int) $row['owner_id'];
$row['item_count'] = (int) $row['item_count'];
$row['card_count'] = (int) $row['card_count'];
$row['completed_count'] = (int) $row['completed_count'];
/** @var TodoListRow $row */
/** @var ProjectRow $row */
return $row;
}
}
+1 -1
View File
@@ -51,7 +51,7 @@ final class Config
$mail = new MailConfig(
transport: strtolower(self::env('MAIL_TRANSPORT', 'mail')),
fromAddress: self::env('MAIL_FROM', 'no-reply@todo.test'),
fromName: self::env('MAIL_FROM_NAME', 'Todo List'),
fromName: self::env('MAIL_FROM_NAME', 'Projects'),
logPath: $mailLogPath,
smtpHost: self::env('MAIL_SMTP_HOST'),
smtpPort: (int) (self::env('MAIL_SMTP_PORT') ?? '587'),
+22 -22
View File
@@ -6,17 +6,17 @@ use App\Auth\AuthMiddleware;
use App\Auth\JwtService;
use App\Auth\SessionPayload;
use App\Http\Controllers\AuthController;
use App\Http\Controllers\CardController;
use App\Http\Controllers\EmailVerificationController;
use App\Http\Controllers\TodoItemController;
use App\Http\Controllers\TodoListController;
use App\Http\Controllers\ProjectController;
use App\Http\JsonErrorHandler;
use App\Mail\EmailVerifier;
use App\Mail\LogMailer;
use App\Mail\Mailer;
use App\Mail\PhpMailerMailer;
use App\Repository\CardRepository;
use App\Repository\EmailVerificationRepository;
use App\Repository\TodoItemRepository;
use App\Repository\TodoListRepository;
use App\Repository\ProjectRepository;
use App\Repository\UserRepository;
use App\Support\Config;
use App\Support\Database;
@@ -41,8 +41,8 @@ $errorMiddleware->setDefaultErrorHandler(
// --- Wiring -----------------------------------------------------------------
$users = new UserRepository($database->pdo());
$todoLists = new TodoListRepository($database->pdo());
$todoItems = new TodoItemRepository($database->pdo());
$projects = new ProjectRepository($database->pdo());
$cards = new CardRepository($database->pdo());
$verificationTokens = new EmailVerificationRepository($database->pdo());
$jwt = new JwtService($config->jwtSecret, $config->jwtTtl);
$session = new SessionPayload($jwt, $verificationTokens);
@@ -55,8 +55,8 @@ $verifier = new EmailVerifier($verificationTokens, $users, $mailer, $config->app
$authController = new AuthController($users, $session, $verifier);
$emailController = new EmailVerificationController($users, $verificationTokens, $verifier, $session);
$listController = new TodoListController($todoLists);
$itemController = new TodoItemController($todoLists, $todoItems);
$projectController = new ProjectController($projects);
$cardController = new CardController($projects, $cards);
$authMiddleware = new AuthMiddleware($jwt, $users);
// --- Routes ---------------------------------------------------------------
@@ -64,8 +64,8 @@ $authMiddleware = new AuthMiddleware($jwt, $users);
$app->group('/api', function (RouteCollectorProxy $group) use (
$authController,
$emailController,
$listController,
$itemController,
$projectController,
$cardController,
$authMiddleware,
) {
$group->get('/health', function (Request $request, Response $response): Response {
@@ -82,19 +82,19 @@ $app->group('/api', function (RouteCollectorProxy $group) use (
$group->post('/email/verification', [$emailController, 'resend'])->add($authMiddleware);
$group->post('/email/change', [$emailController, 'requestChange'])->add($authMiddleware);
$group->group('/lists', function (RouteCollectorProxy $lists) use ($listController, $itemController) {
$lists->get('', [$listController, 'index']);
$lists->post('', [$listController, 'store']);
$lists->get('/{listId:[0-9]+}', [$listController, 'show']);
$lists->patch('/{listId:[0-9]+}', [$listController, 'update']);
$lists->delete('/{listId:[0-9]+}', [$listController, 'destroy']);
$group->group('/projects', function (RouteCollectorProxy $projects) use ($projectController, $cardController) {
$projects->get('', [$projectController, 'index']);
$projects->post('', [$projectController, 'store']);
$projects->get('/{projectId:[0-9]+}', [$projectController, 'show']);
$projects->patch('/{projectId:[0-9]+}', [$projectController, 'update']);
$projects->delete('/{projectId:[0-9]+}', [$projectController, 'destroy']);
$lists->get('/{listId:[0-9]+}/items', [$itemController, 'index']);
$lists->post('/{listId:[0-9]+}/items', [$itemController, 'store']);
$lists->put('/{listId:[0-9]+}/items/order', [$itemController, 'reorder']);
$lists->get('/{listId:[0-9]+}/items/{itemId:[0-9]+}', [$itemController, 'show']);
$lists->patch('/{listId:[0-9]+}/items/{itemId:[0-9]+}', [$itemController, 'update']);
$lists->delete('/{listId:[0-9]+}/items/{itemId:[0-9]+}', [$itemController, 'destroy']);
$projects->get('/{projectId:[0-9]+}/cards', [$cardController, 'index']);
$projects->post('/{projectId:[0-9]+}/cards', [$cardController, 'store']);
$projects->put('/{projectId:[0-9]+}/cards/order', [$cardController, 'reorder']);
$projects->get('/{projectId:[0-9]+}/cards/{cardId:[0-9]+}', [$cardController, 'show']);
$projects->patch('/{projectId:[0-9]+}/cards/{cardId:[0-9]+}', [$cardController, 'update']);
$projects->delete('/{projectId:[0-9]+}/cards/{cardId:[0-9]+}', [$cardController, 'destroy']);
})->add($authMiddleware);
});