Files
myep-team/src/Email/Mailer.php
T

98 lines
3.0 KiB
PHP

<?php
namespace App\Email;
use App\Model\EmailAttachmentDto;
use Psr\Log\LoggerInterface;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Address;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Contracts\Translation\TranslatorInterface;
class Mailer
{
public function __construct(
private readonly MailerInterface $mailer,
private readonly TranslatorInterface $translator,
private readonly array $defaults,
private readonly LoggerInterface $logger
) {
}
public function createAndSendEmail(array $context, array $options): void
{
$config = $this->resolveConfig($options);
$email = $this->create($context, $config);
$recipients = (array) $config['to'];
foreach ($recipients as $recipient) {
$email->to($recipient);
$this->send($email);
}
}
public function create(array $context, array $config): TemplatedEmail
{
$email = (new TemplatedEmail())
->from($config['from'])
->subject($this->translator->trans($config['subject'], $config['subject_parameters']))
->htmlTemplate($config['template'])
->context($context)
;
foreach ($config['attachments'] as $attachment) {
/* @var EmailAttachmentDto $attachment */
$email->attach($attachment->getContent(), $attachment->getName(), $attachment->getMimeType());
}
return $email;
}
public function send(TemplatedEmail $email): void
{
$recipients = array_map(fn (Address $address) => $address->toString(), $email->getTo());
try {
$this->mailer->send($email);
$this->logger->info('Send email', [
'to' => $recipients,
'subject' => $email->getSubject(),
]);
} catch (TransportExceptionInterface $e) {
$this->logger->error('Email could not be sent', [
'to' => $recipients,
'subject' => $email->getSubject(),
'error' => $e->getMessage(),
]);
}
}
private function resolveConfig(array $options): array
{
$resolver = new OptionsResolver();
$resolver
->setDefaults([
'from' => $this->defaults['from'],
'to' => $this->defaults['to'],
'subject_parameters' => [],
'attachments' => [],
])
->setRequired([
'template',
'subject',
])
->setAllowedTypes('to', ['string', 'array'])
->setAllowedTypes('template', 'string')
->setAllowedTypes('subject', 'string')
->setAllowedTypes('subject_parameters', 'array')
->setAllowedTypes('attachments', 'array')
;
return $resolver->resolve($options);
}
}