<?php
namespace App\EventSubscriber;
use App\Entity\OrganizationalChart;
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
{
/**
* @var EntityManagerInterface
*/
private $entityManager;
/**
* @var UserPasswordEncoderInterface
*/
private $passwordEncoder;
/**
* @param EntityManagerInterface $entityManager
* @param UserPasswordEncoderInterface $passwordEncoder
*/
public function __construct(EntityManagerInterface $entityManager, UserPasswordEncoderInterface $passwordEncoder)
{
$this->entityManager = $entityManager;
$this->passwordEncoder = $passwordEncoder;
}
/**
* @return string[][]
*/
public static function getSubscribedEvents(): array
{
return [
BeforeEntityPersistedEvent::class => ['beforeCreate'],
BeforeEntityUpdatedEvent::class => ['beforeUpdated'],
];
}
/**
* @param $event
* @return void
*/
public function beforeCreate($event)
{
$entity = $event->getEntityInstance();
if ($entity instanceof User && $entity->getPassword()) {
$this->setPassword($entity);
}
if ($entity instanceof OrganizationalChart) {
$entity->setUpdatedAt(new \DateTime());
}
}
/**
* @param $event
* @return void
*/
public function beforeUpdated($event)
{
$entity = $event->getEntityInstance();
if ($entity instanceof OrganizationalChart) {
$entity->setUpdatedAt(new \DateTime());
}
}
/**
* @param User $entity
*/
public function setPassword(User $entity): void
{
$pass = $entity->getPassword();
$entity->setPassword(
$this->passwordEncoder->encodePassword(
$entity,
$pass
)
);
$this->entityManager->persist($entity);
$this->entityManager->flush();
}
}