<?php
namespace App\EventSubscriber;
use ApiPlatform\Core\EventListener\EventPriorities;
use App\Entity\Bin;
use App\Entity\Action;
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\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
class EasyApiSubscriber implements EventSubscriberInterface
{
private $entityManager;
private $userPasswordHasher;
public function __construct(EntityManagerInterface $entityManager,UserPasswordHasherInterface $userPasswordHasher)
{
$this->entityManager = $entityManager;
$this->userPasswordHasher = $userPasswordHasher;
}
public static function getSubscribedEvents()
{
return [
KernelEvents::VIEW => ['run', EventPriorities::PRE_VALIDATE],
];
}
public function run(ViewEvent $event)
{
$entity = $event->getControllerResult();
$method = $event->getRequest()->getMethod();
if (($entity instanceof Bin) && $method === 'POST') {
$this->setCreateBin($event);
}elseif(($entity instanceof Bin) && $method === 'PUT'){
$this->setUpdateBin($event);
}elseif(($entity instanceof User) && $method === 'PUT'){
$this->setUpdateUser($event);
}
}
public function setCreateBin(ViewEvent $event)
{
$entity = $event->getControllerResult();
if (!($entity instanceof Bin)) {
return;
}
$action = new Action();
$action->setBin($entity);
$action->setColumns($entity->getColumns());
$date=new \DateTimeImmutable('@'.strtotime('now'));
$action->setDateAt($date);
//$action->setDateUp(null);
$entity->addAction($action);
}
public function setUpdateBin(ViewEvent $event)
{
$entity = $event->getControllerResult();
if (!($entity instanceof Bin)) {
return;
}
$date=new \DateTimeImmutable('@'.strtotime('now'));
$qb = $this->entityManager->createQueryBuilder(); // $em is your entity manager
$old = $this->entityManager->getRepository(Action::class)
->createQueryBuilder('c')
->select('c')
->andWhere('c.bin = :bin')
->andWhere($qb->expr()->isNull("c.dateUp"))
->setParameter('bin', $entity)
->orderBy('c.id', 'DESC')
->setMaxResults(1)
->getQuery()
->getOneOrNullResult();
if($old){
$old->setDateUp($date);
$this->entityManager->persist($old);
}
$action = new Action();
$action->setBin($entity);
$action->setColumns($entity->getColumns());
$action->setDateAt($date);
$entity->addAction($action);
}
public function setUpdateUser(ViewEvent $event)
{
$entity = $event->getControllerResult();
if (!($entity instanceof User)) {
return;
}
if(!empty($entity->getPassword())){
// $entity->setPassword($this->userPasswordHasher->hashPassword($entity, $entity->getPassword()));
}
}
}