aboutsummaryrefslogtreecommitdiffstats
path: root/src/app/Models/Like.php
blob: dc019a053df00789f81cecd0bfea3d4e83e0b0a2 (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
<?php

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

namespace App\Models;

use App\Database;

class Like
{
    private \PDO $pdo;

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

    /**
     * Toggle a like: insert if not yet liked, delete if already liked.
     * Returns true if the post is now liked, false if unliked.
     */
    public function toggle(int $userId, int $postId): bool
    {
        // INSERT IGNORE silently fails when the UNIQUE(user_id, post_id) constraint
        // is violated, meaning the user already liked this post
        $stmt = $this->pdo->prepare(
            'INSERT IGNORE INTO likes (user_id, post_id) VALUES (:user_id, :post_id)'
        );
        $stmt->execute(['user_id' => $userId, 'post_id' => $postId]);

        if ($stmt->rowCount() > 0) {
            return true;
        }

        // Row wasn't inserted → already liked → remove the like
        $stmt = $this->pdo->prepare(
            'DELETE FROM likes WHERE user_id = :user_id AND post_id = :post_id'
        );
        $stmt->execute(['user_id' => $userId, 'post_id' => $postId]);
        return false;
    }

    public function countByPost(int $postId): int
    {
        $stmt = $this->pdo->prepare('SELECT COUNT(*) FROM likes WHERE post_id = :post_id');
        $stmt->execute(['post_id' => $postId]);
        return (int) $stmt->fetchColumn();
    }

    public function hasUserLiked(int $userId, int $postId): bool
    {
        $stmt = $this->pdo->prepare(
            'SELECT 1 FROM likes WHERE user_id = :user_id AND post_id = :post_id LIMIT 1'
        );
        $stmt->execute(['user_id' => $userId, 'post_id' => $postId]);
        return $stmt->fetch() !== false;
    }
}