Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 8 additions & 24 deletions src/Symfony/Bridge/Twig/Mime/BodyRenderer.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,15 +45,13 @@ public function render(Message $message): void
return;
}

$messageContext = $message->getContext();

$previousRenderingKey = $messageContext[__CLASS__] ?? null;
unset($messageContext[__CLASS__]);
$currentRenderingKey = $this->getFingerPrint($message);
if ($previousRenderingKey === $currentRenderingKey) {
if (null === $message->getTextTemplate() && null === $message->getHtmlTemplate()) {
// email has already been rendered
return;
}

$messageContext = $message->getContext();

if (isset($messageContext['email'])) {
throw new InvalidArgumentException(sprintf('A "%s" context cannot have an "email" entry as this is a reserved variable.', get_debug_type($message)));
}
Expand All @@ -64,34 +62,20 @@ public function render(Message $message): void

if ($template = $message->getTextTemplate()) {
$message->text($this->twig->render($template, $vars));
$message->textTemplate(null);
}

if ($template = $message->getHtmlTemplate()) {
$message->html($this->twig->render($template, $vars));
$message->htmlTemplate(null);
}

$message->context([]);
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This allows a TemplatedEmail to be serialized after rendering the body when the context contains non-serializable variables like Doctrine entities.


// if text body is empty, compute one from the HTML body
if (!$message->getTextBody() && null !== $html = $message->getHtmlBody()) {
$message->text($this->convertHtmlToText(\is_resource($html) ? stream_get_contents($html) : $html));
}
$message->context($message->getContext() + [__CLASS__ => $currentRenderingKey]);
}

private function getFingerPrint(TemplatedEmail $message): string
{
$messageContext = $message->getContext();
unset($messageContext[__CLASS__]);

$payload = [$messageContext, $message->getTextTemplate(), $message->getHtmlTemplate()];
try {
$serialized = serialize($payload);
} catch (\Exception) {
// Serialization of 'Closure' is not allowed
// Happens when context contain a closure, in that case, we assume that context always change.
$serialized = random_bytes(8);
}

return md5($serialized);
}

private function convertHtmlToText(string $html): string
Expand Down