src/EventSubscriber/LabelSequenceEventSubscriber.php line 28

  1. <?php
  2. declare(strict_types=1);
  3. namespace App\EventSubscriber;
  4. use ApiPlatform\Core\EventListener\EventPriorities;
  5. use App\Entity\Label;
  6. use App\Service\Label\LabelSequenceCalculatorService;
  7. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  8. use Symfony\Component\HttpFoundation\Request;
  9. use Symfony\Component\HttpKernel\Event\ViewEvent;
  10. use Symfony\Component\HttpKernel\KernelEvents;
  11. final class LabelSequenceEventSubscriber implements EventSubscriberInterface
  12. {
  13.     public function __construct(private readonly LabelSequenceCalculatorService $labelSequenceCalculatorService)
  14.     {
  15.     }
  16.     public static function getSubscribedEvents(): array
  17.     {
  18.         return [
  19.             KernelEvents::VIEW => ['createLabelSequence'EventPriorities::PRE_WRITE]
  20.         ];
  21.     }
  22.     public function createLabelSequence(ViewEvent $event): void
  23.     {
  24.         $entity $event->getControllerResult();
  25.         if (
  26.             !$entity instanceof Label
  27.             ||
  28.             $event->getRequest()->getMethod() !== Request::METHOD_POST
  29.         ) {
  30.             return;
  31.         }
  32.         $entity->setSequence($this->labelSequenceCalculatorService->calculateNextLevelSequence($entity));
  33.     }
  34. }