NotificationRepository.php
2.88 KB
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
<?php
namespace FootyRoom\Repositories;
use Illuminate\Database\Connection;
class NotificationRepository
{
/**
* @var \Illuminate\Database\Connection
*/
protected $mysql;
/**
* Constructor.
*
* @param \Illuminate\Database\Connection $mysql
*/
public function __construct(Connection $mysql)
{
$this->mysql = $mysql;
}
/**
* Finds all notifications specified by user id and notification types.
*
* @param int $userId
* @param string[] $types
*
* @return object[]
*/
public function findRecent($userId, $types = [])
{
$query = $this->mysql
->table('notifications')
->where('user_id', '=', $userId)
->where(function ($query) {
$query
->where('read', '=', 0)
->orWhere('created_at', '>', $this->mysql->raw('DATE_SUB(CURDATE(), INTERVAL 1 WEEK)'));
})
->orderBy('id', 'desc');
if ($types) {
$query->whereIn('type', $types);
}
$notifications = $query->get();
foreach ($notifications as $key => $item) {
$notifications[$key]->meta = json_decode($item->meta);
}
return $notifications;
}
/**
* Marks all notifications as read specified by userId and notification
* types.
*
* @param int $userId
* @param string[] $types
*
* @return bool
*/
public function clearAll($userId, $types = [])
{
$query = $this->mysql
->table('notifications')
->where('user_id', '=', $userId);
if ($types) {
$query->whereIn('type', $types);
}
return $query->update(['read' => 1]);
}
/**
* Returns count of notifications aggregated by type.
*
* @param int $userId
*
* @return object This will contain `wall`, `requests` and `replies`.
*/
public function getCount($userId)
{
$count = $this->mysql
->select(
"SELECT wall.wall as wall, friend.request as requests, replies.replies as replies
FROM
(
SELECT COUNT(*) as wall
FROM `notifications`
WHERE user_id = ? AND (type = 'wall-post') AND `read` = 0
) as wall,
(
SELECT COUNT(*) as request
FROM `fr_friends`
WHERE user_id_2 = ? AND status = 0
) as friend,
(
SELECT COUNT(*) as replies
FROM `notifications`
WHERE user_id = ? AND (type = 'comment-reply' OR type = 'forum-reply' OR type = 'wall-reply') AND `read` = 0
) as replies",
[$userId, $userId, $userId]
);
return $count[0];
}
/**
* Marks wall notifications as read specified by user id.
*
* @param int $userId
*
* @return bool
*/
public function clearWall($userId)
{
$this->clearAll($userId, $types = ['wall-post', 'wall-reply']);
}
}