src/EventSubscriber/AlertDuplicateSubscriber.php line 34

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use ApiPlatform\Core\EventListener\EventPriorities;
  4. use App\Entity\Alert;
  5. use App\Repository\AlertRepository;
  6. use App\Utils\ConvertToPolygon;
  7. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  8. use Symfony\Component\HttpFoundation\Request;
  9. use Symfony\Component\HttpFoundation\Response;
  10. use Symfony\Component\HttpKernel\Event\ViewEvent;
  11. use Symfony\Component\HttpKernel\KernelEvents;
  12. use Symfony\Component\Security\Core\Security;
  13. class AlertDuplicateSubscriber implements EventSubscriberInterface
  14. {
  15.     /**
  16.      * @var AlertRepository
  17.      */
  18.     private $alertRepository;
  19.     /**
  20.      * @var Security
  21.      */
  22.     private $security;
  23.     public function __construct(AlertRepository $alertRepositorySecurity $security)
  24.     {
  25.         $this->alertRepository $alertRepository;
  26.         $this->security $security;
  27.     }
  28.     public function checkDuplicate(ViewEvent $event): void
  29.     {
  30.         $object $event->getControllerResult();
  31.         $request $event->getRequest();
  32.         if (!$object instanceof Alert || !$request->isMethod(Request::METHOD_POST)) {
  33.             return;
  34.         }
  35.         $user $object->getUser() ?: $this->security->getUser();
  36.         if ($user === null) {
  37.             return;
  38.         }
  39.         if ($object->getUser() === null) {
  40.             $object->setUser($user);
  41.         }
  42.         if ($object->getCoordinates() !== null && $object->getCoordinates() !== []) {
  43.             $object->setPolygon(ConvertToPolygon::run($object->getCoordinates()));
  44.         }
  45.         $existing $this->alertRepository->findDuplicateForUser($object$user);
  46.         if ($existing !== null) {
  47.             $event->setResponse(
  48.                 new Response(json_encode([
  49.                     'message' => 'Alert already exists!'
  50.                     'code' => Response::HTTP_CONFLICT
  51.                     'success' => false,
  52.                     'data' => []
  53.                 ]), Response::HTTP_BAD_REQUEST));
  54.         }
  55.     }
  56.     /**
  57.      * @return array<string, mixed>
  58.      */
  59.     public static function getSubscribedEvents(): array
  60.     {
  61.         return [
  62.             KernelEvents::VIEW => ['checkDuplicate'EventPriorities::PRE_WRITE],
  63.         ];
  64.     }
  65. }