<?php
# src/EventSubscriber/EasyAdminSubscriber.php
namespace App\EventSubscriber;
use App\Entity\User;
use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityPersistedEvent;
use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityUpdatedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
class UserAfterCreate implements EventSubscriberInterface
{
/**
* @var UserPasswordEncoderInterface
*/
private $passwordEncoder;
/**
* EasyAdminSubscriber constructor.
*
* @param UserPasswordEncoderInterface $passwordEncoder
*/
public function __construct(UserPasswordHasherInterface $passwordEncoder) {
$this->passwordEncoder = $passwordEncoder;
}
public static function getSubscribedEvents()
{
return [
BeforeEntityPersistedEvent::class => ['preUpdateEntity'],
];
}
public function preUpdateEntity(BeforeEntityPersistedEvent $event)
{
$entity = $event->getEntityInstance();
if (!($entity instanceof User)) {
return;
}
$plain_password = $entity->getPlainPassword();
if(!empty($plain_password)) {
$new_password = $this->passwordEncoder->hashPassword($entity, $plain_password);
$entity->setPassword($new_password);
$entity->eraseCredentials(null);
}
}
}