src/EventSubscriber/NotificationSubscriber.php line 27

  1. <?php
  2. namespace App\EventSubscriber;
  3. use ApiPlatform\Symfony\EventListener\EventPriorities;
  4. use ApiPlatform\Util\RequestAttributesExtractor;
  5. use App\Entity\Notification;
  6. use App\Event\NotificationCreatedEvent;
  7. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  8. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  9. use Symfony\Component\HttpKernel\Event\ViewEvent;
  10. use Symfony\Component\HttpKernel\KernelEvents;
  11. class NotificationSubscriber implements EventSubscriberInterface
  12. {
  13.     public function __construct(private EventDispatcherInterface $dispatcher){}
  14.     public static function getSubscribedEvents(): array
  15.     {
  16.         return [
  17.             KernelEvents::VIEW => ['dispatchNotificationCreation'EventPriorities::PRE_WRITE],
  18.         ];
  19.     }
  20.     public function dispatchNotificationCreation(ViewEvent $event): void
  21.     {
  22.         $controllerResult $event->getControllerResult();
  23.         $request $event->getRequest();
  24.         if (!$controllerResult instanceof Notification
  25.             || !($attributes RequestAttributesExtractor::extractAttributes($request))
  26.             || !$attributes['persist']
  27.             || 'POST' !== $request->getMethod()
  28.         ) {
  29.             return;
  30.         }
  31.         $this->dispatcher->dispatch(new NotificationCreatedEvent($controllerResult));
  32.     }
  33. }