src/EventSubscriber/EasyAdminSubscriber.php line 51

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Entity\OrganizationalChart;
  4. use App\Entity\User;
  5. use Doctrine\ORM\EntityManagerInterface;
  6. use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityPersistedEvent;
  7. use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityUpdatedEvent;
  8. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  9. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  10. class EasyAdminSubscriber implements EventSubscriberInterface
  11. {
  12.     /**
  13.      * @var EntityManagerInterface
  14.      */
  15.     private $entityManager;
  16.     /**
  17.      * @var UserPasswordEncoderInterface
  18.      */
  19.     private $passwordEncoder;
  20.     /**
  21.      * @param EntityManagerInterface $entityManager
  22.      * @param UserPasswordEncoderInterface $passwordEncoder
  23.      */
  24.     public function __construct(EntityManagerInterface $entityManagerUserPasswordEncoderInterface $passwordEncoder)
  25.     {
  26.         $this->entityManager $entityManager;
  27.         $this->passwordEncoder $passwordEncoder;
  28.     }
  29.     /**
  30.      * @return string[][]
  31.      */
  32.     public static function getSubscribedEvents(): array
  33.     {
  34.         return [
  35.             BeforeEntityPersistedEvent::class => ['beforeCreate'],
  36.             BeforeEntityUpdatedEvent::class => ['beforeUpdated'],
  37.         ];
  38.     }
  39.     /**
  40.      * @param $event
  41.      * @return void
  42.      */
  43.     public function beforeCreate($event)
  44.     {
  45.         $entity $event->getEntityInstance();
  46.         if ($entity instanceof User && $entity->getPassword()) {
  47.             $this->setPassword($entity);
  48.         }
  49.         if ($entity instanceof OrganizationalChart) {
  50.             $entity->setUpdatedAt(new \DateTime());
  51.         }
  52.     }
  53.     /**
  54.      * @param $event
  55.      * @return void
  56.      */
  57.     public function beforeUpdated($event)
  58.     {
  59.         $entity $event->getEntityInstance();
  60.         if ($entity instanceof OrganizationalChart) {
  61.             $entity->setUpdatedAt(new \DateTime());
  62.         }
  63.     }
  64.     /**
  65.      * @param User $entity
  66.      */
  67.     public function setPassword(User $entity): void
  68.     {
  69.         $pass $entity->getPassword();
  70.         $entity->setPassword(
  71.             $this->passwordEncoder->encodePassword(
  72.                 $entity,
  73.                 $pass
  74.             )
  75.         );
  76.         $this->entityManager->persist($entity);
  77.         $this->entityManager->flush();
  78.     }
  79. }