postoffice-1.0.x-dev/src/BodyRenderer/ThemedBodyRenderer.php
src/BodyRenderer/ThemedBodyRenderer.php
<?php
namespace Drupal\postoffice\BodyRenderer;
use Drupal\Core\Asset\AttachedAssets;
use Drupal\Core\Render\RendererInterface;
use Drupal\postoffice\Email\TemplateAttachmentsInterface;
use Drupal\postoffice\Email\ThemedEmailInterface;
use Symfony\Component\Mime\BodyRendererInterface;
use Symfony\Component\Mime\Email;
use Symfony\Component\Mime\Message;
/**
* Symfony mailer body renderer for emails themed using Drupal render arrays.
*/
class ThemedBodyRenderer implements BodyRendererInterface {
/**
* The drupal core renderer.
*/
protected RendererInterface $coreRenderer;
/**
* Constructs a new themed body renderer.
*/
public function __construct(RendererInterface $coreRenderer) {
$this->coreRenderer = $coreRenderer;
}
/**
* {@inheritdoc}
*/
public function render(Message $message): void {
if ($message instanceof ThemedEmailInterface && $message instanceof Email) {
$build = $message->buildThemedEmail();
$message->html((string) $this->coreRenderer->renderRoot($build));
if ($message instanceof TemplateAttachmentsInterface) {
$templateAttachments = AttachedAssets::createFromRenderArray($build);
$message->setTemplateAttachments($templateAttachments);
}
}
}
}
