<?php
//----------------------------------------------------------------------
// src/EventSubscriber/WebappImageSubscriber.php
// Plan.io Task #4410
//----------------------------------------------------------------------
namespace App\EventSubscriber;
use Doctrine\Bundle\DoctrineBundle\EventSubscriber\EventSubscriberInterface;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Events;
use Doctrine\Persistence\Event\LifecycleEventArgs;
use Doctrine\Persistence\Proxy;
use Doctrine\ORM\Event\OnFlushEventArgs;
use Doctrine\ORM\Event\PostFlushEventArgs;
use App\Entity\Webapp\Image;
use App\Services\LogTools;
class WebappImageSubscriber implements EventSubscriberInterface
{
public function __construct(EntityManagerInterface $em, LogTools $logTools)
{
$this->em = $em;
$this->logTools = $logTools;
}
private array $entitiesToLog = [];
public function getSubscribedEvents(): array
{
return [
Events::prePersist,
Events::preUpdate,
Events::preRemove,
Events::postFlush,
];
}
public function prePersist(LifecycleEventArgs $args): void
{
$entity = $args->getObject();
if ($entity instanceof Image)
{
$this->entitiesToLog[] = $entity;
$log = "[prePersist]".$entity->getLogLabel();
$this->logTools->webapp_image_debug($log);
}
}
public function preUpdate(LifecycleEventArgs $args): void
{
$entity = $args->getObject();
if ($entity instanceof Image)
{
$this->entitiesToLog[] = $entity;
$log = "[preUpdate]".$entity->getLogLabel();
$this->logTools->webapp_image_debug($log);
}
}
public function preRemove(LifecycleEventArgs $args): void
{
$entity = $args->getObject();
if ($entity instanceof Image)
{
// In postFlush the id is no longer availabile since the object
// has already been removed from the database
$entity->updateLoggingData([
"id" => $entity->getId(),
]);
$this->entitiesToLog[] = $entity;
$log = "[preRemove]".$entity->getLogLabel();
$this->logTools->webapp_image_debug($log);
}
}
public function postFlush($args): void
{
foreach ($this->entitiesToLog as $entity)
{
$log = "[postFlush]".$entity->getLogLabel();
$this->logTools->webapp_image_debug($log);
}
$this->entitiesToLog = [];
}
}