deferring the sending of notification to kernel.terminate: prepare

This commit is contained in:
2022-04-22 11:34:41 +02:00
parent e246ccbcd9
commit 33f93d484d
6 changed files with 137 additions and 13 deletions

View File

@@ -0,0 +1,47 @@
<?php
namespace Chill\MainBundle\Notification\EventListener;
use Chill\MainBundle\Notification\NotificationPersisterInterface;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\TerminateEvent;
class PersistNotificationOnTerminateEventSubscriber implements EventSubscriberInterface
{
private EntityManagerInterface $em;
private NotificationPersisterInterface $persister;
public function __construct(EntityManagerInterface $em, NotificationPersisterInterface $persister)
{
$this->em = $em;
$this->persister = $persister;
}
public static function getSubscribedEvents()
{
return [
'kernel.terminate' => [
['onKernelTerminate', 1024], // we must ensure that the priority is before sending email
]
];
}
public function onKernelTerminate(TerminateEvent $event): void
{
if ($event->isMasterRequest()) {
$this->persistNotifications();
}
}
private function persistNotifications(): void
{
foreach ($this->persister->getWaitingNotifications() as $notification) {
$this->em->persist($notification);
}
$this->em->flush();
}
}

View File

@@ -0,0 +1,23 @@
<?php
namespace Chill\MainBundle\Notification;
use Chill\MainBundle\Entity\Notification;
class NotificationPersister implements NotificationPersisterInterface
{
private array $waitingNotifications = [];
public function persist(Notification $notification): void
{
$this->waitingNotifications[] = $notification;
}
/**
* @return array|Notification[]
*/
public function getWaitingNotifications(): array
{
return $this->waitingNotifications;
}
}

View File

@@ -0,0 +1,22 @@
<?php
namespace Chill\MainBundle\Notification;
use Chill\MainBundle\Entity\Notification;
/**
* Store the notification
*
* Those notification will be stored into database by the kernel. This
* will also ensure that this happens outside of regular operations
* operated by the entity manager.
*/
interface NotificationPersisterInterface
{
public function persist(Notification $notification): void;
/**
* @return array|Notification[]
*/
public function getWaitingNotifications(): array;
}