<?php
namespace App\EventSubscriber;
use ApiPlatform\Symfony\EventListener\EventPriorities;
use App\Entity\Job;
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 JobAcceptedSubscriber implements EventSubscriberInterface
{
/** @var string The relative path inside templates/messages without any extensions */
private const TEMPLATE = 'job/accepted';
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
{
$job = $event->getControllerResult();
$method = $event->getRequest()->getMethod();
# POST methods are used to create instances, and we are only interested in new jobs
if (!$job instanceof Job || $method !== Request::METHOD_POST) {
return;
}
$customer = $job->getPond()->getCustomer();
$message = $this->messageService
->withRecipient($customer)
->withSubject('Your job has been accepted')
->withTemplate(self::TEMPLATE)
->withTemplateData([
'addressLine1' => $job->getPond()->getAddress1(),
'firstName' => $customer->getFirstName() === 'ANNETTE' ? null : $customer->getFirstName(),
'fullAddress' => $job->getPond()->getAddress(),
]);
$currentUser = $this->tokenStorage->getToken()->getUser();
if ($currentUser instanceof User) {
$message = $message->withCurrentUser($currentUser);
}
$message->send();
}
}