Thanks to visit codestin.com
Credit goes to github.com

Skip to content

[TwigBridge] Fix "Serialization of 'Closure'" error when rendering an TemplatedEmail #40446

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 11, 2021
Merged
Show file tree
Hide file tree
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
19 changes: 18 additions & 1 deletion src/Symfony/Bridge/Twig/Mime/BodyRenderer.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public function render(Message $message): void

$previousRenderingKey = $messageContext[__CLASS__] ?? null;
unset($messageContext[__CLASS__]);
$currentRenderingKey = md5(serialize([$messageContext, $message->getTextTemplate(), $message->getHtmlTemplate()]));
$currentRenderingKey = $this->getFingerPrint($message);
if ($previousRenderingKey === $currentRenderingKey) {
return;
}
Expand Down Expand Up @@ -77,6 +77,23 @@ public function render(Message $message): void
$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 $e) {
// 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
{
if (null !== $this->converter) {
Expand Down
21 changes: 21 additions & 0 deletions src/Symfony/Bridge/Twig/Tests/Mime/BodyRendererTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,27 @@ public function testRenderedOnce()
$this->assertEquals('reset', $email->getTextBody());
}

public function testRenderedOnceUnserializableContext()
{
$twig = new Environment(new ArrayLoader([
'text' => 'Text',
]));
$renderer = new BodyRenderer($twig);
$email = (new TemplatedEmail())
->to('[email protected]')
->from('[email protected]')
;
$email->textTemplate('text');
$email->context([
'foo' => static function () {
return 'bar';
},
]);

$renderer->render($email);
$this->assertEquals('Text', $email->getTextBody());
}

private function prepareEmail(?string $text, ?string $html, array $context = []): TemplatedEmail
{
$twig = new Environment(new ArrayLoader([
Expand Down