<?php
# src/EventSubscriber/EasyAdminSubscriber.php
namespace App\EventSubscriber;
use App\Entity\User;
use App\Services\UserService;
use Doctrine\ORM\EntityManagerInterface;
use EasyCorp\Bundle\EasyAdminBundle\Event\AfterEntityPersistedEvent;
use EasyCorp\Bundle\EasyAdminBundle\Event\AfterEntityUpdatedEvent;
use Symfony\Component\DependencyInjection\ParameterBag\ContainerBagInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
class UserAdminSubscriber implements EventSubscriberInterface
{
private $em;
private $params;
private $hasher;
private $userService;
public function __construct( EntityManagerInterface $em,ContainerBagInterface $params,UserPasswordHasherInterface $hasher, UserService $userService)
{
$this->em = $em;
$this->params = $params;
$this->hasher = $hasher;
$this->userService = $userService;
}
public static function getSubscribedEvents()
{
return [
AfterEntityUpdatedEvent::class => ['updateUserIntoAdmin'],
AfterEntityPersistedEvent::class => ['persistUserIntoAdmin'],
];
}
public function updateUserIntoAdmin(AfterEntityUpdatedEvent $event){
$this->upgradeUserIntoAdmin($event);
}
public function persistUserIntoAdmin(AfterEntityPersistedEvent $event){
$this->upgradeUserIntoAdmin($event);
}
private function isValidMd5($md5 ='') {
return strlen($md5) == 32 && ctype_xdigit($md5);
}
private function upgradeUserIntoAdmin($event)
{
$entity = $event->getEntityInstance();
if (!($entity instanceof User)) {
return;
}
if(!empty($entity->getPassword()) && $entity->getPassword() != null && !(strpos($entity->getPassword(), '$argon') !== false) && !(strpos($entity->getPassword(), '$2y$13$') !== false)){
$entity->setPassword($this->hasher->hashPassword($entity, $entity->getPassword()));
}
$now = new \DateTime();
$userRepository = $this->em->getRepository(User::class);
$userTokenExist = $userRepository->findByUserToken($entity->getUserToken());
if($entity->getUserToken() == '' || count($userTokenExist) > 1 ){
$userToken = md5($entity->getEmail().'rocroi'.$now->format('Ymd'));
$entity->setUserToken($userToken);
}
$this->em->persist($entity);
$this->em->flush();
}
}