src/EventSubscriber/OrdUpdater.php line 32

  1. <?php
  2. namespace App\EventSubscriber;
  3. use Symfony\Component\EventDispatcher\EventSubscriberInterface,
  4.     Symfony\Component\HttpKernel\Event\ViewEvent,
  5.     Symfony\Component\HttpKernel\KernelEvents,
  6.     Symfony\Component\HttpFoundation\Request;
  7. use ApiPlatform\Symfony\EventListener\EventPriorities;
  8. use App\Entity\Interface\OrderableInterface,
  9.     App\Repository\OrderableRepository;
  10. final class OrdUpdater implements EventSubscriberInterface
  11. {
  12.     private OrderableRepository $repository;
  13.     public function __construct(OrderableRepository $repository)
  14.     {
  15.         $this->repository $repository;
  16.     }
  17.     public static function getSubscribedEvents(): array
  18.     {
  19.         return [
  20.             KernelEvents::VIEW => [
  21.                 ['update'EventPriorities::POST_VALIDATE]
  22.             ]
  23.         ];
  24.     }
  25.     public function update(ViewEvent $event): void
  26.     {
  27.         $entity  $event->getControllerResult();
  28.         $request $event->getRequest();
  29.         if (
  30.             ! $request->isMethod(Request::METHOD_PUT)
  31.             || ! $entity instanceof OrderableInterface
  32.         ) {
  33.             return;
  34.         }
  35.         $originalEntity $this->repository->getOriginalEntity($entity);
  36.         $oldOrd $originalEntity['ord'];
  37.         $newOrd $entity->getOrd();
  38.         if ($oldOrd === $newOrd) {
  39.             return;
  40.         }
  41.         $entitiesBetween $this->repository->getEntitiesBetween($entity$oldOrd$newOrd);
  42.         foreach ($entitiesBetween as $entityBetween) {
  43.             $entityBetween->setOrd(
  44.                 $entityBetween->getOrd() + ($oldOrd $newOrd : - 1)
  45.             );
  46.         }
  47.         return;
  48.     }
  49. }