<?php
namespace App\EventSubscriber;
use App\Entity\Parasol;
use App\Entity\Rayon;
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 App\Service\ParasolService;
class EasyAdminParasolSubscriber implements EventSubscriberInterface
{
private $entityManager;
private $ps;
public function __construct(EntityManagerInterface $entityManager , ParasolService $ps )
{
$this->entityManager = $entityManager;
$this->ps = $ps;
}
public static function getSubscribedEvents()
{
return [
BeforeEntityPersistedEvent::class => ['addParasol'],
BeforeEntityUpdatedEvent::class => ['updateParasol'], //surtout utile lors d'un reset de mot passe plutôt qu'un réel update, car l'update va de nouveau encrypter le mot de passe DEJA encrypté ...
];
}
public function updateParasol(BeforeEntityUpdatedEvent $event)
{
$entity = $event->getEntityInstance();
if (!($entity instanceof Parasol)) {
return;
}
$this->setFrontOrder($entity);
}
public function addParasol(BeforeEntityPersistedEvent $event)
{
$entity = $event->getEntityInstance();
if (!($entity instanceof Parasol)) {
return;
}
$this->setFrontOrder($entity);
}
/**
* @param Parasol $entity
*/
public function setFrontOrder(Parasol $entity): void
{
if ( $entity->getRayon() != null ) {
$res = $this->ps->countLastPosition($entity->getRayon()->getId());
$entity->setFrontOrder($res[0][1]+1);
}
$this->entityManager->persist($entity);
$this->entityManager->flush();
}
}