<?php
namespace Witalink\StarterBundle\EventSubscriber\Subscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Mailer\Event\MessageEvent;
use Symfony\Component\Mime\Address;
use Symfony\Component\Mime\Email;
class EmailSubscriber implements EventSubscriberInterface
{
private $applicationName;
private $noReplyAddress;
private $noReplyDisplay;
public function __construct(string $applicationName, string $noReplyAddress, string $noReplyDisplay)
{
$this->applicationName = $applicationName;
$this->noReplyAddress = $noReplyAddress;
$this->noReplyDisplay = $noReplyDisplay;
}
public static function getSubscribedEvents()
{
return [
MessageEvent::class => 'onMessage',
];
}
public function onMessage(MessageEvent $event)
{
$email = $event->getMessage();
if (!$email instanceof Email) {
return;
}
// Ajout automatique du From
$email->from(new Address($this->noReplyAddress, $this->noReplyDisplay));
// Ajout de l'application_name si pas dans le titre du mails
$subject = $email->getSubject();
if (stripos($subject, $this->applicationName) === false) {
$email->subject("[$this->applicationName] $subject");
}
}
}