avm99963 | 7099538 | 2020-09-23 01:03:01 +0200 | [diff] [blame] | 1 | <?php |
| 2 | namespace DAFME\Covid; |
| 3 | |
| 4 | class Subjects { |
| 5 | public static function getAll() { |
| 6 | global $con; |
| 7 | $query = $con->prepare('SELECT * FROM subjects'); |
| 8 | |
| 9 | if (!$query->execute()) |
| 10 | return false; |
| 11 | |
| 12 | return $query->fetchAll(\PDO::FETCH_ASSOC); |
| 13 | } |
avm99963 | 339e6f7 | 2020-09-27 17:12:43 +0200 | [diff] [blame^] | 14 | |
| 15 | public static function exists(int $subject): bool { |
| 16 | global $con; |
| 17 | $query = $con->prepare('SELECT id FROM subjects WHERE id = ?'); |
| 18 | if (!$query->execute([$subject])) |
| 19 | return false; |
| 20 | |
| 21 | return $query->rowCount() > 0; |
| 22 | } |
| 23 | |
| 24 | public static function isNewUserSubject(int $subjectId): bool { |
| 25 | global $con; |
| 26 | $query = $con->prepare('SELECT id FROM user_subjects WHERE user_id = :user_id AND subject_id = :subject_id'); |
| 27 | |
| 28 | $userId = Users::getUserId(); |
| 29 | if ($userId == -1 || !$query->execute([ |
| 30 | 'user_id' => $userId, |
| 31 | 'subject_id' => $subjectId |
| 32 | ])) |
| 33 | return false; |
| 34 | |
| 35 | return $query->rowCount() == 0; |
| 36 | } |
| 37 | |
| 38 | public static function getUserSubjects() { |
| 39 | global $con; |
| 40 | $query = $con->prepare('SELECT |
| 41 | us.id, us.subject_id, s.friendly_name, s.calendar_name |
| 42 | FROM user_subjects us |
| 43 | INNER JOIN subjects s |
| 44 | ON us.subject_id = s.id |
| 45 | WHERE us.user_id = ?'); |
| 46 | |
| 47 | $userId = Users::getUserId(); |
| 48 | if ($userId == -1 || !$query->execute([$userId])) |
| 49 | return false; |
| 50 | |
| 51 | return $query->fetchAll(\PDO::FETCH_ASSOC); |
| 52 | } |
| 53 | |
| 54 | public static function addUserSubject(int $subjectId): bool { |
| 55 | global $con; |
| 56 | |
| 57 | if (!self::exists($subjectId) || !self::isNewUserSubject($subjectId)) |
| 58 | return false; |
| 59 | |
| 60 | $query = $con->prepare('INSERT INTO user_subjects (user_id, subject_id) VALUES (:user_id, :subject_id)'); |
| 61 | |
| 62 | $userId = Users::getUserId(); |
| 63 | |
| 64 | return $userId != -1 && $query->execute([ |
| 65 | 'user_id' => $userId, |
| 66 | 'subject_id' => $subjectId |
| 67 | ]); |
| 68 | } |
| 69 | |
| 70 | public static function removeUserSubject(int $subjectId): bool { |
| 71 | global $con; |
| 72 | |
| 73 | $query = $con->prepare('DELETE FROM user_subjects WHERE user_id = :user_id AND subject_id = :subject_id LIMIT 1'); |
| 74 | |
| 75 | $userId = Users::getUserId(); |
| 76 | return $userId != -1 && $query->execute([ |
| 77 | 'user_id' => $userId, |
| 78 | 'subject_id' => $subjectId |
| 79 | ]); |
| 80 | } |
avm99963 | 7099538 | 2020-09-23 01:03:01 +0200 | [diff] [blame] | 81 | } |