src/EventSubscriber/ResidenceAdminSubscriber.php line 44

  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Entity\Building;
  4. use App\Entity\Residence;
  5. use Doctrine\ORM\EntityManagerInterface;
  6. use EasyCorp\Bundle\EasyAdminBundle\Event\AfterEntityPersistedEvent;
  7. use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityUpdatedEvent;
  8. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  9. class ResidenceAdminSubscriber implements EventSubscriberInterface
  10. {
  11.     private EntityManagerInterface $entityManager;
  12.     public function __construct(EntityManagerInterface $entityManager)
  13.     {
  14.         $this->entityManager $entityManager;
  15.     }
  16.     // Ajout du type de retour 'array' pour supprimer le message de dépréciation
  17.     public static function getSubscribedEvents(): array
  18.     {
  19.         return [
  20.             AfterEntityPersistedEvent::class => ['afterEntityPersisted'],
  21.             BeforeEntityUpdatedEvent::class => ['beforeEntityUpdated'],
  22.         ];
  23.     }
  24.     public function afterEntityPersisted(AfterEntityPersistedEvent $event)
  25.     {
  26.         $entity $event->getEntityInstance();
  27.         if (!($entity instanceof Residence)) {
  28.             return;
  29.         }
  30.         if($entity->getId() && $entity->getCityEntity()?->getCity() && $entity->getCountry() && !$entity->getNumberId()){
  31.             $entity->setNumberId(sprintf('N°%s%s%s%s'$entity->getCreatedAt()->format('Y'), $entity->getCreatedAt()->format('m'), $entity->getCreatedAt()->format('d'), str_pad($entity->getId(), 8'0'STR_PAD_LEFT)));
  32.         }
  33.         $this->entityManager->persist($entity);
  34.         $this->entityManager->flush();
  35.     }
  36.     public function beforeEntityUpdated(BeforeEntityUpdatedEvent $event)
  37.     {
  38.         $entity $event->getEntityInstance();
  39.         if (!($entity instanceof Residence)) {
  40.             return;
  41.         }
  42.         $buildings $entity->getBuildings();
  43.         foreach ($buildings as $building) {
  44.             $building->setResidence($entity);
  45.             $this->entityManager->persist($building);
  46.         }
  47.         $this->entityManager->flush();
  48.         $this->entityManager->persist($entity);
  49.         $this->entityManager->flush();
  50.     }
  51. }