Render email once
This commit is contained in:
parent
00e33563c7
commit
186ea59180
@ -46,6 +46,14 @@ final class BodyRenderer implements BodyRendererInterface
|
|||||||
}
|
}
|
||||||
|
|
||||||
$messageContext = $message->getContext();
|
$messageContext = $message->getContext();
|
||||||
|
|
||||||
|
$previousRenderingKey = $messageContext[__CLASS__] ?? null;
|
||||||
|
unset($messageContext[__CLASS__]);
|
||||||
|
$currentRenderingKey = md5(serialize([$messageContext, $message->getTextTemplate(), $message->getHtmlTemplate()]));
|
||||||
|
if ($previousRenderingKey === $currentRenderingKey) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (isset($messageContext['email'])) {
|
if (isset($messageContext['email'])) {
|
||||||
throw new InvalidArgumentException(sprintf('A "%s" context cannot have an "email" entry as this is a reserved variable.', \get_class($message)));
|
throw new InvalidArgumentException(sprintf('A "%s" context cannot have an "email" entry as this is a reserved variable.', \get_class($message)));
|
||||||
}
|
}
|
||||||
@ -66,6 +74,7 @@ final class BodyRenderer implements BodyRendererInterface
|
|||||||
if (!$message->getTextBody() && null !== $html = $message->getHtmlBody()) {
|
if (!$message->getTextBody() && null !== $html = $message->getHtmlBody()) {
|
||||||
$message->text($this->convertHtmlToText(\is_resource($html) ? stream_get_contents($html) : $html));
|
$message->text($this->convertHtmlToText(\is_resource($html) ? stream_get_contents($html) : $html));
|
||||||
}
|
}
|
||||||
|
$message->context($message->getContext() + [__CLASS__ => $currentRenderingKey]);
|
||||||
}
|
}
|
||||||
|
|
||||||
private function convertHtmlToText(string $html): string
|
private function convertHtmlToText(string $html): string
|
||||||
|
@ -79,6 +79,27 @@ HTML;
|
|||||||
$this->prepareEmail('Text', '', ['email' => 'reserved!']);
|
$this->prepareEmail('Text', '', ['email' => 'reserved!']);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function testRenderedOnce()
|
||||||
|
{
|
||||||
|
$twig = new Environment(new ArrayLoader([
|
||||||
|
'text' => 'Text',
|
||||||
|
]));
|
||||||
|
$renderer = new BodyRenderer($twig);
|
||||||
|
$email = (new TemplatedEmail())
|
||||||
|
->to('fabien@symfony.com')
|
||||||
|
->from('helene@symfony.com')
|
||||||
|
;
|
||||||
|
$email->textTemplate('text');
|
||||||
|
|
||||||
|
$renderer->render($email);
|
||||||
|
$this->assertEquals('Text', $email->getTextBody());
|
||||||
|
|
||||||
|
$email->text('reset');
|
||||||
|
|
||||||
|
$renderer->render($email);
|
||||||
|
$this->assertEquals('reset', $email->getTextBody());
|
||||||
|
}
|
||||||
|
|
||||||
private function prepareEmail(?string $text, ?string $html, array $context = []): TemplatedEmail
|
private function prepareEmail(?string $text, ?string $html, array $context = []): TemplatedEmail
|
||||||
{
|
{
|
||||||
$twig = new Environment(new ArrayLoader([
|
$twig = new Environment(new ArrayLoader([
|
||||||
|
Reference in New Issue
Block a user