<?php
namespace App\EventListener\Notification;
use App\Entity\Company\Company;
use App\Enum\NotificationEvents;
use App\Event\NotificationCreateEvent;
use App\Repository\Company\UserRepository;
use App\Service\Notification\NotificationService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class NotificationCreateEventSubscriber implements EventSubscriberInterface
{
public function __construct(
private NotificationService $notificationService,
private UserRepository $userRepository
) {
$this->notificationService = $notificationService;
$this->userRepository = $userRepository;
}
public static function getSubscribedEvents()
{
return [
NotificationCreateEvent::NAME => 'onNotificationCreation'
];
}
public function onNotificationCreation(NotificationCreateEvent $event)
{
$data = $event->getData();
$data['link'] = $event->getLink();
if ($event->getTitleOptions()) {
$data['title'] = NotificationEvents::getTitle($event->getEvent(), $event->getTitleOptions());
}
if ($event->getContentOptions()) {
$data['content'] = NotificationEvents::getContent($event->getEvent(), $event->getContentOptions());
}
$data['event'] = $event->getEvent();
$data['route'] = $event->getRoute();
$data['route_params'] = $event->getRouteParams();
// envoyer notification web
$this->notificationService->send($data);
// envoyer notification push
$recipient = $data['recipient'];
$user = $recipient instanceof Company ? $this->userRepository->getCompanyPrincipalUser($recipient->getId()) : $this->userRepository->getCustomerCompanyPrincipalUser($recipient->getId());
if ($user && $user->getDeviceToken()) {
$this->notificationService->sendPushNotification($user->getDeviceToken(), $event->getEvent());
}
}
}