tasklist-backend/src/Repositories/TaskRepository.php

91 lines
2.4 KiB
PHP
Raw Normal View History

2025-04-13 19:03:41 +01:00
<?php declare(strict_types=1);
namespace Repositories;
use Carbon\Carbon;
use Database\Connection;
use Exceptions\TaskNotFoundException;
2025-04-13 19:03:41 +01:00
use Interfaces\TaskDao;
use Models\Task;
use PDO;
class TaskRepository implements TaskDao
{
private PDO $conn;
public function __construct(Connection $connection)
{
$this->conn = $connection->getConnection();
}
2025-04-13 22:18:14 +01:00
public function create(Task $task): int
2025-04-13 19:03:41 +01:00
{
$data = $task->persist();
$stmt = $this->conn->prepare(
"INSERT INTO Tasks (task_owner, created_at, updated_at, name, description, start, end, status_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"
);
$stmt->bindParam(1, $data['task_owner']);
$stmt->bindParam(2, $data['created_at']);
$stmt->bindParam(3, $data['updated_at']);
$stmt->bindParam(4, $data['name']);
$stmt->bindParam(5, $data['description']);
$stmt->bindParam(6, $data['start']);
$stmt->bindParam(7, $data['end']);
$stmt->bindParam(8, $data['status_id']);
2025-04-13 22:18:14 +01:00
if ($stmt->execute()) {
return (int) $this->conn->lastInsertId();
}
2025-04-13 19:03:41 +01:00
2025-04-13 22:18:14 +01:00
return 0;
2025-04-13 19:03:41 +01:00
}
public function readAll(): array
{
$stmt = $this->conn->query('SELECT * FROM Tasks');
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
/**
* @throws TaskNotFoundException
*/
2025-04-13 19:03:41 +01:00
public function readById($id): Task
{
$stmt = $this->conn->prepare('SELECT * FROM Tasks WHERE id = ?');
$stmt->execute([$id]);
if (!$data = $stmt->fetch(PDO::FETCH_ASSOC))
{
throw new TaskNotFoundException('Task not found.');
}
return Task::fromArray($data);
2025-04-13 19:03:41 +01:00
}
public function update(Task $task): bool
{
$stmt = $this->conn->prepare(
"UPDATE Tasks SET task_owner = ?, updated_at = ?, name = ?, description = ?, start = ?, end = ?, status_id = 0 WHERE id = ?"
);
return $stmt->execute([
1, // Mock user ID for now, we haven't implemented authentication yet
Carbon::now(),
$task->getName(),
2025-04-13 19:03:41 +01:00
$task->getDescription(),
$task->getStart(),
$task->getEnd(),
$task->getStatusId(),
2025-04-13 19:03:41 +01:00
$task->getTaskId()
]);
}
public function delete(Task $task): bool
{
$stmt = $this->conn->prepare('DELETE FROM Tasks WHERE id = ?');
return $stmt->execute([$task->getTaskId()]);
}
}