src/EventSubscriber/MercureSubscriber.php line 43

  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Entity\User;
  4. use App\Event\NotificationCreatedEvent;
  5. use App\Event\NotificationReadEvent;
  6. use App\Queue\EnqueueMethod;
  7. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  8. use Symfony\Component\Mercure\HubInterface;
  9. use Symfony\Component\Mercure\Update;
  10. use Symfony\Component\Serializer\SerializerInterface;
  11. class MercureSubscriber implements EventSubscriberInterface
  12. {
  13.     public function __construct(private SerializerInterface $serializer, private EnqueueMethod $enqueue) {}
  14.     public static function getSubscribedEvents(): array
  15.     {
  16.         return [
  17.             NotificationCreatedEvent::class => 'publishNotification',
  18.             NotificationReadEvent::class => 'onNotificationRead',
  19.         ];
  20.     }
  21.     public function publishNotification(NotificationCreatedEvent $event): void
  22.     {
  23.         $notification $event->getNotification();
  24.         $channel $notification->getChannel();
  25.         if ('public' === $channel && $notification->getUser() instanceof User) {
  26.             $channel 'user/'.$notification->getUser()->getId();
  27.         }
  28.         $update = new Update("/notifications/$channel"$this->serializer->serialize([
  29.             'type' => 'notification',
  30.             'data' => $notification,
  31.         ], 'json', [
  32.             'groups' => ['read:notification'],
  33.             'iri' => false,
  34.         ]), true);
  35.         $this->enqueue->enqueue(HubInterface::class, '__invoke', [$update]);
  36.     }
  37.     public function onNotificationRead(NotificationReadEvent $event): void
  38.     {
  39.         $user $event->getUser();
  40.         $update = new Update(
  41.             "/notifications/user/{$user->getId()}",
  42.             '{"type": "markAsRead"}',
  43.             true
  44.         );
  45.         $this->enqueue->enqueue(HubInterface::class, '__invoke', [$update]);
  46.     }
  47. }