src/EventSubscriber/ResidenceAdminSubscriber.php line 44
<?php
namespace App\EventSubscriber;
use App\Entity\Building;
use App\Entity\Residence;
use Doctrine\ORM\EntityManagerInterface;
use EasyCorp\Bundle\EasyAdminBundle\Event\AfterEntityPersistedEvent;
use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityUpdatedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ResidenceAdminSubscriber implements EventSubscriberInterface
{
private EntityManagerInterface $entityManager;
public function __construct(EntityManagerInterface $entityManager)
{
$this->entityManager = $entityManager;
}
// Ajout du type de retour 'array' pour supprimer le message de dépréciation
public static function getSubscribedEvents(): array
{
return [
AfterEntityPersistedEvent::class => ['afterEntityPersisted'],
BeforeEntityUpdatedEvent::class => ['beforeEntityUpdated'],
];
}
public function afterEntityPersisted(AfterEntityPersistedEvent $event)
{
$entity = $event->getEntityInstance();
if (!($entity instanceof Residence)) {
return;
}
if($entity->getId() && $entity->getCityEntity()?->getCity() && $entity->getCountry() && !$entity->getNumberId()){
$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)));
}
$this->entityManager->persist($entity);
$this->entityManager->flush();
}
public function beforeEntityUpdated(BeforeEntityUpdatedEvent $event)
{
$entity = $event->getEntityInstance();
if (!($entity instanceof Residence)) {
return;
}
$buildings = $entity->getBuildings();
foreach ($buildings as $building) {
$building->setResidence($entity);
$this->entityManager->persist($building);
}
$this->entityManager->flush();
$this->entityManager->persist($entity);
$this->entityManager->flush();
}
}