src/EventSubscriber/annuairePapierSubscriber.php line 48

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Entity\Commune;
  4. use App\Entity\AnnuairePapier;
  5. use Doctrine\ORM\EntityManagerInterface;
  6. use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityPersistedEvent;
  7. use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityUpdatedEvent;
  8. use mysql_xdevapi\Exception;
  9. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  10. class annuairePapierSubscriber implements EventSubscriberInterface
  11. {
  12.     private $entityManager;
  13.     public function __construct(EntityManagerInterface $entityManager)
  14.     {
  15.         $this->entityManager $entityManager;
  16.     }
  17.     public static function getSubscribedEvents()
  18.     {
  19.         return [
  20.             BeforeEntityPersistedEvent::class => ['setCommune'],
  21.             BeforeEntityUpdatedEvent::class => ['updateCommune']
  22.         ];
  23.     }
  24.     public function setCommune(BeforeEntityPersistedEvent $event)
  25.     {
  26.         try{
  27.             $entity $event->getEntityInstance();
  28.             if (($entity instanceof AnnuairePapier)) {
  29.                 $entityManager $this->entityManager->getRepository(Commune::class)->find($entity->getCommunesSansAn());
  30.                 $entity->setCommune($entityManager);
  31.                 $entity->setProvince($entityManager->getIdProvince());
  32.             }
  33.         } catch (\Doctrine\ORM\ORMException $e){
  34.             return $e;
  35.         }
  36.     }
  37.     public function updateCommune(BeforeEntityUpdatedEvent $event)
  38.     {
  39.         try{
  40.             $entity $event->getEntityInstance();
  41.             if (($entity instanceof AnnuairePapier)) {
  42.                 $entityManager $this->entityManager->getRepository(Commune::class)->find($entity->getCommunesSansAn());
  43.                 $entity->setCommune($entityManager);
  44.                 $entity->setProvince($entityManager->getIdProvince());
  45.             }
  46.         } catch (\Doctrine\ORM\ORMException $e){
  47.         return $e;
  48.         }
  49.     }
  50. }