src/EventSubscriber/EasyAdminRayonSubscriber.php line 39

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Entity\Rayon;
  4. use App\Entity\User;
  5. use Doctrine\ORM\EntityManagerInterface;
  6. use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityPersistedEvent;
  7. use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityUpdatedEvent;
  8. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  9. class EasyAdminRayonSubscriber implements EventSubscriberInterface
  10. {
  11.     private $entityManager;
  12.     public function __construct(EntityManagerInterface $entityManager)
  13.     {
  14.         $this->entityManager $entityManager;
  15.     }
  16.     public static function getSubscribedEvents()
  17.     {
  18.         return [
  19.             BeforeEntityPersistedEvent::class => ['addRayon'],
  20.             BeforeEntityUpdatedEvent::class => ['updateRayon'], //surtout utile lors d'un reset de mot passe plutôt qu'un réel update, car l'update va de nouveau encrypter le mot de passe DEJA encrypté ...
  21.         ];
  22.     }
  23.     public function updateRayon(BeforeEntityUpdatedEvent $event)
  24.     {
  25.         $entity $event->getEntityInstance();
  26.         if (!($entity instanceof Rayon)) {
  27.             return;
  28.         }
  29.         $this->setUser($entity);
  30.     }
  31.     public function addRayon(BeforeEntityPersistedEvent $event)
  32.     {
  33.         $entity $event->getEntityInstance();
  34.         if (!($entity instanceof Rayon)) {
  35.             return;
  36.         }
  37.         $this->setUser($entity);
  38.     }
  39.     /**
  40.      * @param Rayon $entity
  41.      */
  42.     public function setUser(Rayon $entity): void
  43.     {
  44.         $user $this->entityManager->getRepository(User::class)->findBy(['email'=>$entity->getUniquemail()]);
  45.         $entity->setUser($user[0]);
  46.         $this->entityManager->persist($entity);
  47.         $this->entityManager->flush();
  48.     }
  49. }