<?php
namespace App\EventSubscriber;
use App\Entity\IAOperation;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\Persistence\ManagerRegistry;
use EasyCorp\Bundle\EasyAdminBundle\Event\AfterEntityPersistedEvent;
use EasyCorp\Bundle\EasyAdminBundle\Event\AfterEntityUpdatedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class IAOperationSubscriber implements EventSubscriberInterface
{
private $entityManager;
private ManagerRegistry $manager;
public function __construct(
ManagerRegistry $manager,
EntityManagerInterface $entityManager,
TokenStorageInterface $tokenStorage
) {
$this->manager = $manager;
$this->entityManager = $entityManager;
$this->tokenStorage = $tokenStorage;
}
public static function getSubscribedEvents()
{
return [
AfterEntityPersistedEvent::class => ['afterAdd'],
];
}
public function afterAdd(AfterEntityPersistedEvent $event)
{
$entity = $event->getEntityInstance();
if ($entity instanceof IAOperation) {
$count = 0;
$operations = $this->manager->getRepository(IAOperation::class)->findAll();
foreach ($operations as $operation) {
if (strtolower($operation->getLabel()) == strtolower($entity->getLabel())) {
$count++;
}
}
if ($count > 1) {
$this->entityManager->remove($entity);
$this->entityManager->flush();
}
}
}
}