<?php
namespace App\EventListener;
use App\Entity\Forum\GroupMember;
use App\Entity\Notification;
use App\Event\ForumPostEvent;
use App\Service\NotificationCreator;
use Doctrine\ORM\EntityManagerInterface;
use JMS\Serializer\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
class ForumPostListener
{
public function __construct(
private EntityManagerInterface $em,
private NotificationCreator $notificationCreator,
private TokenStorageInterface $tokenStorage
){}
public function onPostCreated(ForumPostEvent $event)
{
$post = $event->getPost();
$group = $post->getGroup();
$postedBy = $post->getUser();
// todo : use messenger instead
if(!is_null($group)){
$groupMembers = $this->em->getRepository(GroupMember::class)->findBy(['group' => $group]);
foreach ($groupMembers as $groupMember) {
if ( $groupMember->getMember() == $this->tokenStorage->getToken()->getUser()){
continue;
}
$arguments = [
'actor' => $postedBy->getId(),
'actor_name' => $postedBy->getName(),
'receiver' => $groupMember->getMember()->getId(),
'receiver_name' => $groupMember->getMember()->getName(),
'post' => $post->getId(),
'post_title' => $post->getTitle(),
'group' => $group->getId(),
'group_name' => $group->getName(),
];
$this->notificationCreator->createNotification(Notification::NOTIFICATION_TYPE_NEW_POST_GROUP, $arguments);
}
}
}
}