<?php
declare(strict_types=1);
namespace App\Component\Doctrine\EntityPersister;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\HttpKernel\Event\TerminateEvent;
/**
* We use this class to be able to persist objects in an onFlush or postFlush event. They will only be actually
* persisted when the kernel is shutting down. This way we can prevent nested flushing.
*/
#[AsEventListener]
class EntityPersister
{
/**
* @var array<int, object>
*/
private array $queue = [];
public function __construct(private readonly EntityManagerInterface $em)
{
}
public function __invoke(TerminateEvent $event): void
{
if (empty($this->queue)) {
return;
}
foreach ($this->queue as $id => $object) {
unset($this->queue[$id]);
$this->em->persist($object);
}
$this->em->flush();
}
public function persist(object ...$entity): void
{
foreach ($entity as $object) {
$id = spl_object_id($object);
$this->queue[$id] = $object;
}
}
}