<?php
namespace App\EventSubscriber;
use ApiPlatform\Symfony\EventListener\EventPriorities;
use App\Entity\Schedule;
use App\Entity\User;
use App\Service\Message;
use JetBrains\PhpStorm\ArrayShape;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
final class JobScheduledSubscriber implements EventSubscriberInterface
{
/** @var string The relative path inside templates/messages without any extensions */
private const TEMPLATE = 'job/scheduled';
public function __construct(
private readonly TokenStorageInterface $tokenStorage,
private readonly Message $messageService,
)
{
}
#[ArrayShape([KernelEvents::VIEW => "array"])]
public static function getSubscribedEvents(): array
{
return [
KernelEvents::VIEW => ['sendMessage', EventPriorities::POST_WRITE],
];
}
public function sendMessage(ViewEvent $event): void
{
$schedule = $event->getControllerResult();
$method = $event->getRequest()->getMethod();
# POST methods are used to create instances, and we are only interested in new schedules
if (!$schedule instanceof Schedule || $method !== Request::METHOD_POST) {
return;
}
$pond = $schedule->getJob()->getPond();
$customer = $pond->getCustomer();
$message = $this->messageService
->withRecipient($customer)
->withSubject('Your job has been scheduled')
->withTemplate(self::TEMPLATE)
->withTemplateData([
'addressLine1' => $pond->getAddress1(),
'employee' => $schedule->getEmployee()->getUser()->getFirstName(),
'firstName' => $customer->getFirstName() === 'ANNETTE' ? null : $customer->getFirstName(),
'fullAddress' => $pond->getAddress(),
'timeWindow' => $schedule->getTimeWindow(),
]);
$currentUser = $this->tokenStorage->getToken()->getUser();
if ($currentUser instanceof User) {
$message = $message->withCurrentUser($currentUser);
}
$message->send();
}
}