diff --git a/www/notes/Database.php b/www/notes/Database.php --- a/www/notes/Database.php +++ b/www/notes/Database.php @@ -4,6 +4,8 @@ class Database { private $pdo; + private $statement; + function __construct(array $config) { @@ -16,10 +18,28 @@ $this->pdo->exec("SET search_path TO notes"); } - function query(string $query, mixed...$parameters) + function query(string $query, mixed ...$parameters) { - $statement = $this->pdo->prepare($query); - $statement->execute($parameters); - return $statement; + $this->statement = $this->pdo->prepare($query); + $this->statement->execute($parameters); + return $this; + } + + function fetch() + { + $result = $this->statement->fetch(); + if (!$result) { + abort(); + } + return $result; + } + + function fetchAll() + { + $result = $this->statement->fetchAll(); + if (!$result) { + abort(); + } + return $result; } } \ No newline at end of file diff --git a/www/notes/controllers/note-create.php b/www/notes/controllers/note-create.php new file mode 100644 --- /dev/null +++ b/www/notes/controllers/note-create.php @@ -0,0 +1,28 @@ +query( + "INSERT INTO notes (body, user_id) VALUES (:body, :user_id)", + ...[ + 'body' => $_POST['body'], + 'user_id' => $currentUserId + ] + ); + header("Location: /notes"); + die(); +} + +require "views/note-create.view.php"; diff --git a/www/notes/controllers/note.php b/www/notes/controllers/note.php --- a/www/notes/controllers/note.php +++ b/www/notes/controllers/note.php @@ -9,20 +9,13 @@ $title = "Note: {$_GET['id']}"; - - +// Fetch and check that it exists $note = $db->query('SELECT * FROM notes WHERE id = :id', ...[ 'id' => $_GET['id'], ])->fetch(); -// No note found -if (!$note) { - abort(); -} // Note from another user -if ($note['user_id'] !== $currentUserId) { - abort(Response::FORBIDDEN); -} +authorize($note['user_id'] === $currentUserId); require "views/note.view.php"; diff --git a/www/notes/functions.php b/www/notes/functions.php --- a/www/notes/functions.php +++ b/www/notes/functions.php @@ -10,4 +10,11 @@ function abort(int $statusCode = Response::NOT_FOUND): void { http_response_code($statusCode); die(); +} + +function authorize(bool $condition, $statusCode = Response::FORBIDDEN): void +{ + if (!$condition) { + abort($statusCode); + } } \ No newline at end of file diff --git a/www/notes/index.php b/www/notes/index.php --- a/www/notes/index.php +++ b/www/notes/index.php @@ -1,4 +1,5 @@ 'controllers/note.php', + '/notes/create' => 'controllers/note-create.php', ]; diff --git a/www/notes/views/index.view.php b/www/notes/views/index.view.php --- a/www/notes/views/index.view.php +++ b/www/notes/views/index.view.php @@ -2,14 +2,14 @@ -
Here is a list of all your Notes, click on one to show more details