src/EventSubscriber/JobScheduledSubscriber.php line 36

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use ApiPlatform\Symfony\EventListener\EventPriorities;
  4. use App\Entity\Schedule;
  5. use App\Entity\User;
  6. use App\Service\Message;
  7. use JetBrains\PhpStorm\ArrayShape;
  8. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  9. use Symfony\Component\HttpFoundation\Request;
  10. use Symfony\Component\HttpKernel\Event\ViewEvent;
  11. use Symfony\Component\HttpKernel\KernelEvents;
  12. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  13. final class JobScheduledSubscriber implements EventSubscriberInterface
  14. {
  15.     /** @var string The relative path inside templates/messages without any extensions */
  16.     private const TEMPLATE 'job/scheduled';
  17.     public function __construct(
  18.         private readonly TokenStorageInterface $tokenStorage,
  19.         private readonly Message $messageService,
  20.     )
  21.     {
  22.     }
  23.     #[ArrayShape([KernelEvents::VIEW => "array"])]
  24.     public static function getSubscribedEvents(): array
  25.     {
  26.         return [
  27.             KernelEvents::VIEW => ['sendMessage'EventPriorities::POST_WRITE],
  28.         ];
  29.     }
  30.     public function sendMessage(ViewEvent $event): void
  31.     {
  32.         $schedule $event->getControllerResult();
  33.         $method $event->getRequest()->getMethod();
  34.         # POST methods are used to create instances, and we are only interested in new schedules
  35.         if (!$schedule instanceof Schedule || $method !== Request::METHOD_POST) {
  36.             return;
  37.         }
  38.         $pond $schedule->getJob()->getPond();
  39.         $customer $pond->getCustomer();
  40.         $message $this->messageService
  41.             ->withRecipient($customer)
  42.             ->withSubject('Your job has been scheduled')
  43.             ->withTemplate(self::TEMPLATE)
  44.             ->withTemplateData([
  45.                 'addressLine1' => $pond->getAddress1(),
  46.                 'employee' => $schedule->getEmployee()->getUser()->getFirstName(),
  47.                 'firstName' => $customer->getFirstName() === 'ANNETTE' null $customer->getFirstName(),
  48.                 'fullAddress' => $pond->getAddress(),
  49.                 'timeWindow' => $schedule->getTimeWindow(),
  50.             ]);
  51.         $currentUser $this->tokenStorage->getToken()->getUser();
  52.         if ($currentUser instanceof User) {
  53.             $message $message->withCurrentUser($currentUser);
  54.         }
  55.         $message->send();
  56.     }
  57. }