postoffice-1.0.x-dev/src/MailerMiddleware/Theme.php
src/MailerMiddleware/Theme.php
<?php
namespace Drupal\postoffice\MailerMiddleware;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Theme\ThemeInitializationInterface;
use Drupal\Core\Theme\ThemeManagerInterface;
use Symfony\Component\Mailer\Envelope;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\RawMessage;
/**
* Implements the theme mailer middleware.
*/
class Theme implements MailerInterface {
/**
* The decorated mailer.
*/
protected MailerInterface $mailer;
/**
* The theme manager.
*/
protected ThemeManagerInterface $themeManager;
/**
* The theme initialization service.
*/
protected ThemeInitializationInterface $themeInitialization;
/**
* Config factory.
*/
protected ConfigFactoryInterface $configFactory;
/**
* Constructs a new language mailer middleware.
*/
public function __construct(
MailerInterface $mailer,
ThemeManagerInterface $themeManager,
ThemeInitializationInterface $themeInitialization,
ConfigFactoryInterface $configFactory,
) {
$this->mailer = $mailer;
$this->themeManager = $themeManager;
$this->themeInitialization = $themeInitialization;
$this->configFactory = $configFactory;
}
/**
* {@inheritdoc}
*/
public function send(RawMessage $message, ?Envelope $envelope = NULL): void {
$originalTheme = $this->themeManager->getActiveTheme()->getName();
$mailTheme = $this->getMailTheme($message);
try {
if ($originalTheme !== $mailTheme) {
$this->themeManager->setActiveTheme($this->themeInitialization->initTheme($mailTheme));
}
$this->mailer->send($message, $envelope);
}
finally {
$activeTheme = $this->themeManager->getActiveTheme()->getName();
if ($activeTheme !== $originalTheme) {
$this->themeManager->setActiveTheme($this->themeInitialization->initTheme($originalTheme));
}
}
}
/**
* Determine the mail theme.
*/
public function getMailTheme(RawMessage $message) {
$result = $this->configFactory->get('system.theme')->get('default');
$config = $this->configFactory->get('postoffice.site');
if (!$config->get('theme_use_default')) {
$result = $config->get('theme_name');
}
return $result;
}
}
