src/EventSubscriber/IAOperationSubscriber.php line 34

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Entity\IAOperation;
  4. use Doctrine\ORM\EntityManagerInterface;
  5. use Doctrine\Persistence\ManagerRegistry;
  6. use EasyCorp\Bundle\EasyAdminBundle\Event\AfterEntityPersistedEvent;
  7. use EasyCorp\Bundle\EasyAdminBundle\Event\AfterEntityUpdatedEvent;
  8. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  9. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  10. class IAOperationSubscriber implements EventSubscriberInterface
  11. {
  12.     private $entityManager;
  13.     private ManagerRegistry $manager;
  14.     public function __construct(
  15.         ManagerRegistry $manager,
  16.         EntityManagerInterface $entityManager,
  17.         TokenStorageInterface $tokenStorage
  18.     ) {
  19.         $this->manager $manager;
  20.         $this->entityManager $entityManager;
  21.         $this->tokenStorage $tokenStorage;
  22.     }
  23.     public static function getSubscribedEvents()
  24.     {
  25.         return [
  26.             AfterEntityPersistedEvent::class => ['afterAdd'],
  27.         ];
  28.     }
  29.     public function afterAdd(AfterEntityPersistedEvent $event)
  30.     {
  31.         $entity $event->getEntityInstance();
  32.         if ($entity instanceof IAOperation) {
  33.             $count 0;
  34.             $operations $this->manager->getRepository(IAOperation::class)->findAll();
  35.             foreach ($operations as $operation) {
  36.                 if (strtolower($operation->getLabel()) == strtolower($entity->getLabel())) {
  37.                     $count++;
  38.                 }
  39.             }
  40.             if ($count 1) {
  41.                 $this->entityManager->remove($entity);
  42.                 $this->entityManager->flush();
  43.             }
  44.         }
  45.     }
  46. }