<?php
namespace App\Modules\Notification\Event\Subscriber;
use App\Modules\Chat\Event\MessageSent;
use App\Modules\Chat\Service\MessagesService;
use App\Modules\Notification\Entity\NotificationEntity;
use App\Modules\Notification\Message\System\YouHasNewChatMessageNotification;
use App\Modules\Notification\Service\NotificationService;
use App\Service\WebRoutes;
use Doctrine\Common\Collections\ArrayCollection;
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class SendNewChatMessageNotification implements EventSubscriberInterface
{
private $notificationService;
private $chatMessagesService;
private $logger;
public function __construct(NotificationService $notificationService, MessagesService $chatMessagesService, LoggerInterface $logger)
{
$this->notificationService = $notificationService;
$this->chatMessagesService = $chatMessagesService;
$this->logger = $logger;
}
/**
* Returns an array of event names this subscriber wants to listen to.
*
* The array keys are event names and the value can be:
*
* * The method name to call (priority defaults to 0)
* * An array composed of the method name to call and the priority
* * An array of arrays composed of the method names to call and respective
* priorities, or 0 if unset
*
* For instance:
*
* * ['eventName' => 'methodName']
* * ['eventName' => ['methodName', $priority]]
* * ['eventName' => [['methodName1', $priority], ['methodName2']]]
*
* @return array The event names to listen to
*/
public static function getSubscribedEvents()
{
return [
MessageSent::class => ['sendNotification']
];
}
public function sendNotification(MessageSent $event)
{
try {
$message = $this->chatMessagesService->get($event->getChatId(), $event->getChatMessageId());
$author = $message->getAuthor();
$chat = $message->getChat();
$contract = $chat->getContract();
$systemNotificationReceivers = new ArrayCollection();
foreach ($chat->getParticipants() as $participant) {
if ($participant != $author) {
$systemNotificationReceivers->add($participant);
}
}
$link = [
'id' => $chat->getId(),
'entity' => NotificationEntity::CHAT,
'message' => $message->getContent(),
'contract_ref' => !is_null($contract) ? $contract->getRef() : ''
];
$message = new YouHasNewChatMessageNotification($link, $author, $systemNotificationReceivers);
$this->notificationService->sendSystem($message);
} catch (\Exception $e) {
$this->logger->error($e->getMessage());
}
}
}