src/EventSubscriber/JobAcceptedSubscriber.php line 36

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use ApiPlatform\Symfony\EventListener\EventPriorities;
  4. use App\Entity\Job;
  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 JobAcceptedSubscriber implements EventSubscriberInterface
  14. {
  15.     /** @var string The relative path inside templates/messages without any extensions */
  16.     private const TEMPLATE 'job/accepted';
  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.         $job $event->getControllerResult();
  33.         $method $event->getRequest()->getMethod();
  34.         # POST methods are used to create instances, and we are only interested in new jobs
  35.         if (!$job instanceof Job || $method !== Request::METHOD_POST) {
  36.             return;
  37.         }
  38.         $customer $job->getPond()->getCustomer();
  39.         $message $this->messageService
  40.             ->withRecipient($customer)
  41.             ->withSubject('Your job has been accepted')
  42.             ->withTemplate(self::TEMPLATE)
  43.             ->withTemplateData([
  44.                 'addressLine1' => $job->getPond()->getAddress1(),
  45.                 'firstName' => $customer->getFirstName() === 'ANNETTE' null $customer->getFirstName(),
  46.                 'fullAddress' => $job->getPond()->getAddress(),
  47.             ]);
  48.         $currentUser $this->tokenStorage->getToken()->getUser();
  49.         if ($currentUser instanceof User) {
  50.             $message $message->withCurrentUser($currentUser);
  51.         }
  52.         $message->send();
  53.     }
  54. }