<?php
declare(strict_types=1);
namespace App\Infrastructure\Notifications\EventSubscriber;
use App\Infrastructure\Notifications\Event\CreateNotificationEvent;
use App\Infrastructure\Notifications\Event\FireBaseNotificationSendEvent;
use DateTimeImmutable;
use Doctrine\ORM\EntityManagerInterface;
use Kreait\Firebase\Contract\Messaging;
use Kreait\Firebase\Exception\FirebaseException;
use Kreait\Firebase\Exception\MessagingException;
use Kreait\Firebase\Messaging\CloudMessage;
use Kreait\Firebase\Messaging\WebPushConfig as FireBaseWebPush;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class NotificationSubscriber implements EventSubscriberInterface
{
private Messaging $messaging;
private EntityManagerInterface $entityManager;
public function __construct(
// Messaging $messaging,
EntityManagerInterface $entityManager
)
{
// $this->messaging = $messaging;
$this->entityManager = $entityManager;
}
public static function getSubscribedEvents(): array
{
return [
//Создание уведомления в бд
CreateNotificationEvent::class => 'onNotificationCreated',
//Отправка уведомления
FireBaseNotificationSendEvent::class => 'onNotificationSendToFirebase',
];
}
/**
* @throws MessagingException
* @throws FirebaseException
*/
public function onNotificationSendToFirebase(FireBaseNotificationSendEvent $notificationSendEvent): void
{
$notification = $notificationSendEvent->getNotification();
//Если еще не отправлено и у пользователя есть токен
if($notification->getPostedAt() === null && $notification->getUser()->getNotificationToken() !== null){
$message = CloudMessage::withTarget('token', $notification->getUser()->getNotificationToken())
->withWebPushConfig(
FireBaseWebPush::fromArray([
'notification' => [
'title' => $notification->getTitle(),
'body' => $notification->getDescription(),
'icon' => '',
],
'fcm_options' => [
'link' => $notification->getLink(),
]
])
)
->withData([$notification->getAdditionalData()]);
//$this->messaging->send($message);
}
$notification->setPostedAt(new DateTimeImmutable());
$this->entityManager->flush();
}
public function onNotificationCreated(FireBaseNotificationSendEvent $notificationSendEvent): void
{
$notification = $notificationSendEvent->getNotification();
$this->entityManager->persist($notification);
$this->entityManager->flush();
}
}