<?php
namespace App\EventSubscriber;
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;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
class EasyAdminSubscriber implements EventSubscriberInterface
{
private $entityManager;
private $passwordEncoder;
public function __construct(EntityManagerInterface $entityManager, UserPasswordEncoderInterface $passwordEncoder)
{
$this->entityManager = $entityManager;
$this->passwordEncoder = $passwordEncoder;
}
public static function getSubscribedEvents()
{
return [
BeforeEntityPersistedEvent::class => ['addUtilisateur'],
BeforeEntityUpdatedEvent::class => ['updateUtilisateur'],
];
}
public function updateUtilisateur(BeforeEntityUpdatedEvent $event)
{
$entity = $event->getEntityInstance();
if (!($entity instanceof User) ) {
return;
}
$this->setPassword($entity);
}
public function addUtilisateur(BeforeEntityPersistedEvent $event)
{
$entity = $event->getEntityInstance();
if (!($entity instanceof User) ) {
return;
}
$this->setPassword($entity);
}
/**
* @param User $entity
*/
public function setPassword($entity): void
{
$pass = $entity->getPassword();
if($pass!=""){
$newpasword = $this->passwordEncoder->encodePassword($entity,$pass );
$entity->setPassword($newpasword);
$this->entityManager->persist($entity);
$this->entityManager->flush();
}
}
}