aboutsummaryrefslogtreecommitdiffstats
path: root/src/app/Models/Post.php
blob: e82b0d9ee264348e906e13a0abd616e58d18ebc6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<?php

declare(strict_types=1);
// Post model: database operations for the posts table.

namespace App\Models;

use App\Database;

class Post
{
    private \PDO $pdo;

    public function __construct()
    {
        $this->pdo = Database::getInstance()->getPdo();
    }

    public function create(int $userId, string $imagePath): int
    {
        $stmt = $this->pdo->prepare(
            'INSERT INTO posts (user_id, image_path) VALUES (:user_id, :image_path)'
        );
        $stmt->execute(['user_id' => $userId, 'image_path' => $imagePath]);
        return (int) $this->pdo->lastInsertId();
    }

    public function findById(int $id): ?array
    {
        $stmt = $this->pdo->prepare('SELECT * FROM posts WHERE id = :id');
        $stmt->execute(['id' => $id]);
        $row = $stmt->fetch();
        return $row ?: null;
    }

    public function findByUserId(int $userId): array
    {
        $stmt = $this->pdo->prepare(
            'SELECT * FROM posts WHERE user_id = :user_id ORDER BY created_at DESC'
        );
        $stmt->execute(['user_id' => $userId]);
        return $stmt->fetchAll();
    }

    public function countByUserId(int $userId): int
    {
        $stmt = $this->pdo->prepare('SELECT COUNT(*) FROM posts WHERE user_id = :user_id');
        $stmt->execute(['user_id' => $userId]);
        return (int) $stmt->fetchColumn();
    }

    public function findAllPaginated(int $limit, int $offset): array
    {
        $stmt = $this->pdo->prepare(
            'SELECT posts.*, users.username FROM posts
             JOIN users ON posts.user_id = users.id
             ORDER BY posts.created_at DESC
             LIMIT :limit OFFSET :offset'
        );
        // PDO needs explicit int binding for LIMIT/OFFSET
        $stmt->bindValue('limit', $limit, \PDO::PARAM_INT);
        $stmt->bindValue('offset', $offset, \PDO::PARAM_INT);
        $stmt->execute();
        return $stmt->fetchAll();
    }

    public function countAll(): int
    {
        $stmt = $this->pdo->query('SELECT COUNT(*) FROM posts');
        return (int) $stmt->fetchColumn();
    }

    public function delete(int $id): void
    {
        $stmt = $this->pdo->prepare('DELETE FROM posts WHERE id = :id');
        $stmt->execute(['id' => $id]);
    }
}