<?php
namespace App\EventSubscriber;
use ApiPlatform\Core\EventListener\EventPriorities;
use App\Entity\Notification;
use DateTime;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class NotificationReadSubscriber implements EventSubscriberInterface
{
private EntityManagerInterface $em;
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::RESPONSE => ['setReadAt'],
];
}
public function setReadAt(ResponseEvent $event)
{
if($event->getRequest()->attributes->get('_route') !== 'api_notifications_get_item') {
return;
}
$notificationId = $event->getRequest()->attributes->get('id');
/** @var Notification $notification */
$notification = $this->em->getRepository(Notification::class)->find($notificationId);
if($notification->readAt === null) {
$notification->readAt = new DateTime();
}
$this->em->persist($notification);
$this->em->flush();
}
}