src/EventSubscriber/OrdUpdater.php line 32
<?php
namespace App\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface,
Symfony\Component\HttpKernel\Event\ViewEvent,
Symfony\Component\HttpKernel\KernelEvents,
Symfony\Component\HttpFoundation\Request;
use ApiPlatform\Symfony\EventListener\EventPriorities;
use App\Entity\Interface\OrderableInterface,
App\Repository\OrderableRepository;
final class OrdUpdater implements EventSubscriberInterface
{
private OrderableRepository $repository;
public function __construct(OrderableRepository $repository)
{
$this->repository = $repository;
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::VIEW => [
['update', EventPriorities::POST_VALIDATE]
]
];
}
public function update(ViewEvent $event): void
{
$entity = $event->getControllerResult();
$request = $event->getRequest();
if (
! $request->isMethod(Request::METHOD_PUT)
|| ! $entity instanceof OrderableInterface
) {
return;
}
$originalEntity = $this->repository->getOriginalEntity($entity);
$oldOrd = $originalEntity['ord'];
$newOrd = $entity->getOrd();
if ($oldOrd === $newOrd) {
return;
}
$entitiesBetween = $this->repository->getEntitiesBetween($entity, $oldOrd, $newOrd);
foreach ($entitiesBetween as $entityBetween) {
$entityBetween->setOrd(
$entityBetween->getOrd() + ($oldOrd > $newOrd ? 1 : - 1)
);
}
return;
}
}