NotificationRepository.php 2.88 KB
<?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']);
    }
}