<?php
namespace App\Controller;
use App\Entity\Notification;
use App\Repository\NotificationRepository;
use App\Service\Pagination;
use Doctrine\{ DBAL\Connection, ORM\EntityManagerInterface };
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\{ Request, Response };
use Symfony\Component\Routing\Annotation\Route;
#[Route(path: '/notifications'), IsGranted(data: 'IS_AUTHENTICATED_REMEMBERED')]
class NotificationController extends AbstractController
{
#[Route(path: '/', name: 'notification_index')]
public function index(Request $request, Pagination $pagination, NotificationRepository $notifRepo)
{
$query = $notifRepo->findByUser($this->getUser());
$notifications = $pagination->paginate($query, $request, $this->getParameter('items_per_page'));
return $this->render('notification/index.html.twig', [
'notifications' => $notifications,
'cntNotification' => count($notifications),
'last_page' => $pagination->lastPage($notifications)
]);
}
#[Route(path: '/latest', name: 'notification_latest')]
public function latest(NotificationRepository $notifRepo): Response
{
$notifications = $notifRepo->findBy(['user' => $this->getUser(), 'isRead' => false], ['createdAt' => 'DESC'], 5);
return $this->render('notification/latest.html.twig', [
'notifications' => $notifications
]);
}
#[Route(path: '/read/{id}', name: 'notification_read', methods: ['GET'])]
public function read(Notification $notification, EntityManagerInterface $entityManager): Response
{
$notification->setIsRead(true);
$entityManager->flush();
$this->addFlash(
'success',
'Notification marked as read successfully!'
);
return $this->redirectToRoute('notification_index');
}
#[Route(path: '/read-all', name: 'notification_read_all', methods: ['GET'])]
public function readAll(Connection $conn): Response
{
$conn->update('notifications', ['is_read' => 1], [
'user_id' => $this->getUser()->getId(),
'is_read' => 0
]);
$this->addFlash(
'success',
'All notifications marked as read successfully!'
);
return $this->redirectToRoute('notification_index');
}
}