Files
project-manager/src/Repository/CardRepository.php
T

318 lines
10 KiB
PHP
Raw Normal View History

2026-09-03 18:30:52 +01:00
<?php
declare(strict_types=1);
namespace App\Repository;
use PDO;
/**
* Data access for the `cards` table.
2026-09-03 18:30:52 +01:00
*
* `position` is a dense 0..n-1 rank *within a column* — the cards sharing a
* (project_id, status_id). The inbox is the column where status_id IS NULL.
*
* @phpstan-type CardStatus array{id: int, name: string}
* @phpstan-type CardRow array{
* id: int, project_id: int, text: string, complete: bool, position: int,
* status_id: int|null, status: CardStatus|null,
2026-09-03 18:30:52 +01:00
* created_at: string, updated_at: string
* }
*/
final class CardRepository
2026-09-03 18:30:52 +01:00
{
private const SELECT = <<<'SQL'
SELECT c.id, c.project_id, c.text, c.complete, c.position, c.status_id,
c.created_at, c.updated_at,
s.name AS status_name
FROM cards c
LEFT JOIN card_statuses s ON s.id = c.status_id
SQL;
2026-09-03 18:30:52 +01:00
public function __construct(private readonly PDO $pdo)
{
}
/**
* Every card in the project, grouped by column (inbox first) and ordered by
* position within each. Consumers that want a different order (e.g. the
* alphabetical "all tasks" list) re-sort client-side.
*
* @return CardRow[]
2026-09-03 18:30:52 +01:00
*/
public function allForProject(int $projectId): array
2026-09-03 18:30:52 +01:00
{
$stmt = $this->pdo->prepare(
self::SELECT . ' WHERE c.project_id = :project ORDER BY c.status_id, c.position ASC, c.id ASC'
2026-09-03 18:30:52 +01:00
);
$stmt->execute(['project' => $projectId]);
2026-09-03 18:30:52 +01:00
return array_map($this->cast(...), $stmt->fetchAll());
}
/**
* @return CardRow|null
2026-09-03 18:30:52 +01:00
*/
public function findInProject(int $id, int $projectId): ?array
2026-09-03 18:30:52 +01:00
{
$stmt = $this->pdo->prepare(self::SELECT . ' WHERE c.id = :id AND c.project_id = :project');
$stmt->execute(['id' => $id, 'project' => $projectId]);
2026-09-03 18:30:52 +01:00
$row = $stmt->fetch();
return $row === false ? null : $this->cast($row);
}
/**
* @return CardRow
2026-09-03 18:30:52 +01:00
*/
public function create(int $projectId, string $text, bool $complete, ?int $position): array
2026-09-03 18:30:52 +01:00
{
// A new card has no status — it goes to the end of the inbox column.
$position ??= $this->nextPositionInColumn($projectId, null);
2026-09-03 18:30:52 +01:00
$stmt = $this->pdo->prepare(
'INSERT INTO cards (project_id, text, complete, position)
VALUES (:project, :text, :complete, :position)'
2026-09-03 18:30:52 +01:00
);
$stmt->execute([
'project' => $projectId,
2026-09-03 18:30:52 +01:00
'text' => $text,
'complete' => $complete ? 1 : 0,
'position' => $position,
]);
/** @var CardRow $card */
$card = $this->findInProject((int) $this->pdo->lastInsertId(), $projectId);
2026-09-03 18:30:52 +01:00
return $card;
2026-09-03 18:30:52 +01:00
}
/**
* Update simple fields, and/or move the card to another column. A status
* change drops the card at the end of the destination column and re-packs
* the one it left. Precise slotting within a column is done via orderColumn().
*
* @param array{text?: string, complete?: bool, status_id?: int|null} $fields
* @return CardRow
2026-09-03 18:30:52 +01:00
*/
public function update(int $id, int $projectId, array $fields): array
2026-09-03 18:30:52 +01:00
{
/** @var CardRow $card */
$card = $this->findInProject($id, $projectId);
$movesColumn = array_key_exists('status_id', $fields) && $fields['status_id'] !== $card['status_id'];
$sourceColumn = $card['status_id'];
$sets = ['updated_at = ' . $this->nowExpr()];
2026-09-03 18:30:52 +01:00
$params = ['id' => $id];
if (array_key_exists('text', $fields)) {
$sets[] = 'text = :text';
$params['text'] = $fields['text'];
}
if (array_key_exists('complete', $fields)) {
$sets[] = 'complete = :complete';
$params['complete'] = $fields['complete'] ? 1 : 0;
}
if (array_key_exists('status_id', $fields)) {
$sets[] = 'status_id = :status_id';
$params['status_id'] = $fields['status_id'];
}
if ($movesColumn) {
2026-09-03 18:30:52 +01:00
$sets[] = 'position = :position';
$params['position'] = $this->nextPositionInColumn($projectId, $fields['status_id']);
2026-09-03 18:30:52 +01:00
}
$sql = 'UPDATE cards SET ' . implode(', ', $sets) . ' WHERE id = :id';
2026-09-03 18:30:52 +01:00
if (!$movesColumn) {
$this->pdo->prepare($sql)->execute($params);
2026-09-03 18:30:52 +01:00
/** @var CardRow $updated */
$updated = $this->findInProject($id, $projectId);
return $updated;
}
$this->pdo->beginTransaction();
try {
$this->pdo->prepare($sql)->execute($params);
$this->repack($projectId, $sourceColumn);
$this->pdo->commit();
} catch (\Throwable $e) {
$this->pdo->rollBack();
throw $e;
}
/** @var CardRow $updated */
$updated = $this->findInProject($id, $projectId);
return $updated;
2026-09-03 18:30:52 +01:00
}
public function delete(int $id): void
{
$this->pdo->prepare('DELETE FROM cards WHERE id = :id')->execute(['id' => $id]);
2026-09-03 18:30:52 +01:00
}
/**
* IDs of every card in the project.
*
* @return int[]
*/
public function idsForProject(int $projectId): array
{
$stmt = $this->pdo->prepare('SELECT id FROM cards WHERE project_id = :project');
$stmt->execute(['project' => $projectId]);
return array_map(intval(...), $stmt->fetchAll(PDO::FETCH_COLUMN));
}
/**
* IDs of the cards currently in one column, in position order.
*
* @return int[]
*/
public function idsInColumn(int $projectId, ?int $statusId): array
{
[$match, $params] = $this->columnMatch($statusId);
$stmt = $this->pdo->prepare(
"SELECT id FROM cards WHERE project_id = :project AND {$match} ORDER BY position ASC, id ASC"
);
$stmt->execute(['project' => $projectId] + $params);
return array_map(intval(...), $stmt->fetchAll(PDO::FETCH_COLUMN));
}
/**
* Set the contents and order of one column. Every id in $orderedIds is moved
* into $statusId at positions 0..n-1; any other column those cards came from
* is re-packed. One transaction.
*
* @param int[] $orderedIds
* @return CardRow[] the project's cards, grouped by column
*/
public function orderColumn(int $projectId, ?int $statusId, array $orderedIds): array
{
$orderedIds = array_values($orderedIds);
$this->pdo->beginTransaction();
try {
$sourceColumns = $this->columnsOf($projectId, $orderedIds);
$place = $this->pdo->prepare(
'UPDATE cards SET status_id = :status, position = :position, updated_at = ' . $this->nowExpr() . '
WHERE id = :id AND project_id = :project'
);
foreach ($orderedIds as $position => $id) {
$place->execute([
'status' => $statusId,
'position' => $position,
'id' => $id,
'project' => $projectId,
]);
}
foreach ($sourceColumns as $source) {
if ($source !== $statusId) {
$this->repack($projectId, $source);
}
}
$this->pdo->commit();
} catch (\Throwable $e) {
$this->pdo->rollBack();
throw $e;
}
return $this->allForProject($projectId);
}
/**
* The distinct status_id values (columns) the given cards currently sit in.
*
* @param int[] $ids
* @return array<int, int|null>
*/
private function columnsOf(int $projectId, array $ids): array
2026-09-03 18:30:52 +01:00
{
if ($ids === []) {
return [];
}
$placeholders = implode(',', array_fill(0, count($ids), '?'));
2026-09-03 18:30:52 +01:00
$stmt = $this->pdo->prepare(
"SELECT DISTINCT status_id FROM cards WHERE project_id = ? AND id IN ($placeholders)"
2026-09-03 18:30:52 +01:00
);
$stmt->execute([$projectId, ...$ids]);
return array_map(
static fn ($value) => $value === null ? null : (int) $value,
$stmt->fetchAll(PDO::FETCH_COLUMN),
);
}
/** Rewrite one column's positions to a dense 0..n-1 in current order. */
private function repack(int $projectId, ?int $statusId): void
{
$ids = $this->idsInColumn($projectId, $statusId);
$update = $this->pdo->prepare('UPDATE cards SET position = :position WHERE id = :id');
foreach ($ids as $position => $id) {
$update->execute(['position' => $position, 'id' => $id]);
}
}
private function nextPositionInColumn(int $projectId, ?int $statusId): int
{
[$match, $params] = $this->columnMatch($statusId);
$stmt = $this->pdo->prepare(
"SELECT COALESCE(MAX(position), -1) + 1 FROM cards WHERE project_id = :project AND {$match}"
);
$stmt->execute(['project' => $projectId] + $params);
2026-09-03 18:30:52 +01:00
return (int) $stmt->fetchColumn();
}
/**
* A WHERE fragment matching one column, since SQLite needs `IS NULL` (not
* `= NULL`) for the inbox.
*
* @return array{0: string, 1: array<string, int>}
*/
private function columnMatch(?int $statusId): array
{
return $statusId === null
? ['status_id IS NULL', []]
: ['status_id = :status', ['status' => $statusId]];
}
private function nowExpr(): string
{
return "strftime('%Y-%m-%dT%H:%M:%SZ', 'now')";
}
2026-09-03 18:30:52 +01:00
/**
* @param array<string, mixed> $row
* @return CardRow
2026-09-03 18:30:52 +01:00
*/
private function cast(array $row): array
{
$row['id'] = (int) $row['id'];
$row['project_id'] = (int) $row['project_id'];
2026-09-03 18:30:52 +01:00
$row['complete'] = (bool) $row['complete'];
$row['position'] = (int) $row['position'];
$statusId = $row['status_id'] === null ? null : (int) $row['status_id'];
$row['status_id'] = $statusId;
$row['status'] = $statusId === null
? null
: ['id' => $statusId, 'name' => (string) $row['status_name']];
unset($row['status_name']);
/** @var CardRow $row */
2026-09-03 18:30:52 +01:00
return $row;
}
}