<?php
namespace App\EventSubscriber;
use App\Entity\Rayon;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityPersistedEvent;
use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityUpdatedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class EasyAdminRayonSubscriber implements EventSubscriberInterface
{
private $entityManager;
public function __construct(EntityManagerInterface $entityManager)
{
$this->entityManager = $entityManager;
}
public static function getSubscribedEvents()
{
return [
BeforeEntityPersistedEvent::class => ['addRayon'],
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é ...
];
}
public function updateRayon(BeforeEntityUpdatedEvent $event)
{
$entity = $event->getEntityInstance();
if (!($entity instanceof Rayon)) {
return;
}
$this->setUser($entity);
}
public function addRayon(BeforeEntityPersistedEvent $event)
{
$entity = $event->getEntityInstance();
if (!($entity instanceof Rayon)) {
return;
}
$this->setUser($entity);
}
/**
* @param Rayon $entity
*/
public function setUser(Rayon $entity): void
{
$user = $this->entityManager->getRepository(User::class)->findBy(['email'=>$entity->getUniquemail()]);
$entity->setUser($user[0]);
$this->entityManager->persist($entity);
$this->entityManager->flush();
}
}