src/EventSubscriber/NotificationReadSubscriber.php line 29

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use ApiPlatform\Core\EventListener\EventPriorities;
  4. use App\Entity\Notification;
  5. use DateTime;
  6. use Doctrine\ORM\EntityManagerInterface;
  7. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  8. use Symfony\Component\HttpKernel\Event\ResponseEvent;
  9. use Symfony\Component\HttpKernel\KernelEvents;
  10. class NotificationReadSubscriber implements EventSubscriberInterface
  11. {
  12.     private EntityManagerInterface $em;
  13.     public function __construct(EntityManagerInterface $em)
  14.     {
  15.         $this->em $em;
  16.     }
  17.     public static function getSubscribedEvents(): array
  18.     {
  19.         return [
  20.             KernelEvents::RESPONSE => ['setReadAt'],
  21.         ];
  22.     }
  23.     public function setReadAt(ResponseEvent $event)
  24.     {
  25.         if($event->getRequest()->attributes->get('_route') !== 'api_notifications_get_item') {
  26.             return;
  27.         }
  28.         $notificationId $event->getRequest()->attributes->get('id');
  29.         /** @var Notification $notification */
  30.         $notification $this->em->getRepository(Notification::class)->find($notificationId);
  31.         if($notification->readAt === null) {
  32.             $notification->readAt = new DateTime();
  33.         }
  34.         $this->em->persist($notification);
  35.         $this->em->flush();
  36.     }
  37. }