src/Profile/Messages/EventSubscriber/MessagesMercureSubscriber.php line 49

Open in your IDE?
  1. <?php
  2. namespace App\Profile\Messages\EventSubscriber;
  3. use App\Profile\Messages\Event\MessageSendEvent;
  4. use App\Profile\Messages\Event\MessagesEvents;
  5. use App\Profile\Messages\Event\NewConversationEvent;
  6. use App\Profile\Model\Profile;
  7. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  8. use Symfony\Component\HttpFoundation\RequestStack;
  9. use Symfony\Component\Mercure\HubInterface;
  10. use Symfony\Component\Mercure\Update;
  11. class MessagesMercureSubscriber implements EventSubscriberInterface
  12. {
  13.   public function __construct(
  14.     protected HubInterface $hub,
  15.     protected \Twig\Environment $twig,
  16.     protected RequestStack $requestStack
  17.   ) {
  18.   }
  19.   public static function getSubscribedEvents()
  20.   {
  21.     return [
  22.         MessagesEvents::SEND => 'send',
  23.         MessagesEvents::NEW_CONVERSATION => 'newConversation',
  24.     ];
  25.   }
  26.   public function send(MessageSendEvent $event)
  27.   {
  28.     $message $event->message;
  29.     $html $this->twig->render('profile/messages/streams/message.html.twig', [
  30.       'message' => $message,
  31.       'targetUserId' => $message->getSenderId(),
  32.     ]);
  33.     $this->hub->publish(new Update(sprintf($event->getTopic(), $message->getSenderId()), $html));
  34.     $html $this->twig->render('profile/messages/streams/message.html.twig', [
  35.       'message' => $message,
  36.       'profile' => Profile::getById($message->getSenderId()),
  37.       'targetUserId' => $message->getReceiverId(),
  38.     ]);
  39.     $this->hub->publish(new Update(sprintf($event->getTopic(), $message->getReceiverId()), $html));
  40.   }
  41.   public function newConversation(NewConversationEvent $event)
  42.   {
  43.     $profile $event->profile;
  44.     $html $this->twig->render('profile/messages/streams/new-conversation.html.twig', [
  45.       'profile' => $profile,
  46.     ]);
  47.     $this->hub->publish(
  48.       new Update(
  49.         sprintf($event->getTopic(),
  50.           $profile->getId()
  51.         ),
  52.         $html
  53.       )
  54.     );
  55.   }
  56. }