<?php
declare(strict_types=1);
namespace Domain\EventSubscriber;
use Domain\Event\LogEntryCreated;
use Domain\Repository\UserRepositoryInterface;
use Infrastructure\Persistence\Doctrine\Entity\LogEntry;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Address;
final class LogEntryCreatedEventSubscriber implements EventSubscriberInterface
{
private UserRepositoryInterface $userRepository;
private MailerInterface $mailer;
public function __construct(
UserRepositoryInterface $userRepository,
MailerInterface $mailer
) {
$this->userRepository = $userRepository;
$this->mailer = $mailer;
}
public static function getSubscribedEvents(): array
{
return [
LogEntryCreated::class => 'handle',
];
}
public function handle(LogEntryCreated $event): void
{
$logEntry = $event->logEntry();
$recipients = [];
$logEntryCreator = $logEntry->getUser();
if ($logEntryCreator->isManager() || $logEntryCreator->isCleaner()) {
return;
}
if ($logEntryCreator->isClient()) {
$recipientRole = 'ROLE_CFC_MANAGER';
$recipients = $this->getAddresses($recipientRole);
}
$this->communicateToRecipients($recipients, $logEntry);
}
private function communicateToRecipients(array $recipients, LogEntry $logEntry): void
{
if (empty($recipients)) {
return;
}
// dd($recipients);
$this->mailer->send((new TemplatedEmail())
->from(new Address('platform@cfc-platform.com', 'CFC Platform'))
->to(...$recipients)
->subject('Er is een nieuwe logboek item op CFC Platform')
->htmlTemplate('logbook/new_logEntry_email.html.twig')
->context([
'createdByClient' => $logEntry->getUser()->isClient(),
'companyName' => $logEntry->getCompany()->getName(),
'companyId' => $logEntry->getCompany()->getId(),
'logEntryId' => $logEntry->getId(),
]));
}
/**
* @return Address[]
*/
private function getAddresses(string $recipientRole, ?int $companyId = null): array
{
return array_map(static function (array $recipient): Address {
return new Address($recipient['email'], $recipient['fullName']);
}, $this->userRepository->byRole($recipientRole, $companyId)->toArray());
}
}