<?php
namespace App\Profile\Messages\EventSubscriber;
use App\Profile\Messages\Event\MessageSendEvent;
use App\Profile\Messages\Event\MessagesEvents;
use App\Profile\Messages\Event\NewConversationEvent;
use App\Profile\Model\Profile;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Mercure\HubInterface;
use Symfony\Component\Mercure\Update;
class MessagesMercureSubscriber implements EventSubscriberInterface
{
public function __construct(
protected HubInterface $hub,
protected \Twig\Environment $twig,
protected RequestStack $requestStack
) {
}
public static function getSubscribedEvents()
{
return [
MessagesEvents::SEND => 'send',
MessagesEvents::NEW_CONVERSATION => 'newConversation',
];
}
public function send(MessageSendEvent $event)
{
$message = $event->message;
$html = $this->twig->render('profile/messages/streams/message.html.twig', [
'message' => $message,
'targetUserId' => $message->getSenderId(),
]);
$this->hub->publish(new Update(sprintf($event->getTopic(), $message->getSenderId()), $html));
$html = $this->twig->render('profile/messages/streams/message.html.twig', [
'message' => $message,
'profile' => Profile::getById($message->getSenderId()),
'targetUserId' => $message->getReceiverId(),
]);
$this->hub->publish(new Update(sprintf($event->getTopic(), $message->getReceiverId()), $html));
}
public function newConversation(NewConversationEvent $event)
{
$profile = $event->profile;
$html = $this->twig->render('profile/messages/streams/new-conversation.html.twig', [
'profile' => $profile,
]);
$this->hub->publish(
new Update(
sprintf($event->getTopic(),
$profile->getId()
),
$html
)
);
}
}