postoffice-1.0.x-dev/src/MailerMiddleware/AnonymousUser.php
src/MailerMiddleware/AnonymousUser.php
<?php
namespace Drupal\postoffice\MailerMiddleware;
use Drupal\Core\Session\AccountSwitcherInterface;
use Drupal\Core\Session\AnonymousUserSession;
use Symfony\Component\Mailer\Envelope;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\RawMessage;
/**
* Implements a mailer middleware which always switches to the anonymous user.
*/
class AnonymousUser implements MailerInterface {
/**
* The decorated mailer.
*/
protected MailerInterface $mailer;
/**
* Account switcher service.
*/
protected AccountSwitcherInterface $accountSwitcher;
/**
* Constructs new anonymous account mailer middleware.
*/
public function __construct(MailerInterface $mailer, AccountSwitcherInterface $accountSwitcher) {
$this->mailer = $mailer;
$this->accountSwitcher = $accountSwitcher;
}
/**
* {@inheritdoc}
*/
public function send(RawMessage $message, ?Envelope $envelope = NULL): void {
$this->accountSwitcher->switchTo(new AnonymousUserSession());
try {
$this->mailer->send($message, $envelope);
}
finally {
$this->accountSwitcher->switchBack();
}
}
}
