<?php
namespace App\EventSubscriber;
use App\Entity\PositionedInterface;
use Doctrine\ORM\EntityManagerInterface;
use EasyCorp\Bundle\EasyAdminBundle\Event\AfterEntityDeletedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class PositionNormalizerSubscriber implements EventSubscriberInterface
{
public function __construct(
private EntityManagerInterface $entityManager,
)
{}
public static function getSubscribedEvents()
{
return [
AfterEntityDeletedEvent::class => [['onAfterEntityDeleted', 0]],
];
}
public function onAfterEntityDeleted(AfterEntityDeletedEvent $event)
{
$entity = $event->getEntityInstance();
if ($entity instanceof PositionedInterface) {
// Re-normalize positions
$qb = $this->entityManager->createQueryBuilder()
->update($entity::class, 'p')
->set('p.position', 'p.position - 1')
->where('p.position > :position')
->setParameter('position', $entity->getPosition());
$qb->getQuery()->execute();
}
}
}