Skip to content

[Mime] Add a way to control the HTML to text conversion #47201

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
Aug 7, 2022
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
5 changes: 3 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -126,22 +126,23 @@
"doctrine/data-fixtures": "^1.1",
"doctrine/dbal": "^2.13.1|^3.0",
"doctrine/orm": "^2.7.4",
"egulias/email-validator": "^2.1.10|^3.1",
"guzzlehttp/promises": "^1.4",
"league/html-to-markdown": "^5.0",
"masterminds/html5": "^2.7.2",
"monolog/monolog": "^1.25.1|^2",
"nyholm/psr7": "^1.0",
"pda/pheanstalk": "^4.0",
"php-http/httplug": "^1.0|^2.0",
"phpdocumentor/reflection-docblock": "^5.2",
"phpstan/phpdoc-parser": "^1.0",
"predis/predis": "~1.1",
"psr/http-client": "^1.0",
"psr/simple-cache": "^1.0|^2.0|^3.0",
"egulias/email-validator": "^2.1.10|^3.1",
"symfony/mercure-bundle": "^0.3",
"symfony/phpunit-bridge": "^5.4|^6.0",
"symfony/runtime": "self.version",
"symfony/security-acl": "~2.8|~3.0",
"phpdocumentor/reflection-docblock": "^5.2",
"twig/cssinliner-extra": "^2.12|^3",
"twig/inky-extra": "^2.12|^3",
"twig/markdown-extra": "^2.12|^3"
Expand Down
29 changes: 9 additions & 20 deletions src/Symfony/Bridge/Twig/Mime/BodyRenderer.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,12 @@

namespace Symfony\Bridge\Twig\Mime;

use League\HTMLToMarkdown\HtmlConverter;
use League\HTMLToMarkdown\HtmlConverterInterface;
use Symfony\Component\Mime\BodyRendererInterface;
use Symfony\Component\Mime\Exception\InvalidArgumentException;
use Symfony\Component\Mime\HtmlToTextConverter\DefaultHtmlToTextConverter;
use Symfony\Component\Mime\HtmlToTextConverter\HtmlToTextConverterInterface;
use Symfony\Component\Mime\HtmlToTextConverter\LeagueHtmlToMarkdownConverter;
use Symfony\Component\Mime\Message;
use Twig\Environment;

Expand All @@ -24,19 +27,13 @@ final class BodyRenderer implements BodyRendererInterface
{
private Environment $twig;
private array $context;
private HtmlConverter $converter;
private HtmlToTextConverterInterface $converter;

public function __construct(Environment $twig, array $context = [])
public function __construct(Environment $twig, array $context = [], HtmlToTextConverterInterface $converter = null)
{
$this->twig = $twig;
$this->context = $context;
if (class_exists(HtmlConverter::class)) {
$this->converter = new HtmlConverter([
'hard_break' => true,
'strip_tags' => true,
'remove_nodes' => 'head style',
]);
}
$this->converter = $converter ?: (interface_exists(HtmlConverterInterface::class) ? new LeagueHtmlToMarkdownConverter() : new DefaultHtmlToTextConverter());
}

public function render(Message $message): void
Expand Down Expand Up @@ -74,16 +71,8 @@ public function render(Message $message): void

// 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));
}
}

private function convertHtmlToText(string $html): string
{
if (isset($this->converter)) {
return $this->converter->convert($html);
$text = $this->converter->convert(\is_resource($html) ? stream_get_contents($html) : $html, $message->getHtmlCharset());
$message->text($text, $message->getHtmlCharset());
}

return strip_tags(preg_replace('{<(head|style)\b.*?</\1>}is', '', $html));
}
}
26 changes: 19 additions & 7 deletions src/Symfony/Bridge/Twig/Tests/Mime/BodyRendererTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
use Symfony\Bridge\Twig\Mime\BodyRenderer;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Component\Mime\Exception\InvalidArgumentException;
use Symfony\Component\Mime\HtmlToTextConverter\DefaultHtmlToTextConverter;
use Symfony\Component\Mime\HtmlToTextConverter\HtmlToTextConverterInterface;
use Symfony\Component\Mime\Part\Multipart\AlternativePart;
use Twig\Environment;
use Twig\Loader\ArrayLoader;
Expand All @@ -27,14 +29,24 @@ public function testRenderTextOnly()
$this->assertEquals('Text', $email->getBody()->bodyToString());
}

public function testRenderHtmlOnly()
public function testRenderHtmlOnlyWithDefaultConverter()
{
$html = '<head>head</head><b>HTML</b><style type="text/css">css</style>';
$email = $this->prepareEmail(null, $html);
$html = '<head><meta charset="utf-8"></head><b>HTML</b><style>css</style>';
$email = $this->prepareEmail(null, $html, [], new DefaultHtmlToTextConverter());
$body = $email->getBody();
$this->assertInstanceOf(AlternativePart::class, $body);
$this->assertEquals('HTML', $body->getParts()[0]->bodyToString());
$this->assertEquals(str_replace('=', '=3D', $html), $body->getParts()[1]->bodyToString());
$this->assertEquals(str_replace(['=', "\n"], ['=3D', "\r\n"], $html), $body->getParts()[1]->bodyToString());
}

public function testRenderHtmlOnlyWithLeagueConverter()
{
$html = '<head><meta charset="utf-8"></head><b>HTML</b><style>css</style>';
$email = $this->prepareEmail(null, $html);
$body = $email->getBody();
$this->assertInstanceOf(AlternativePart::class, $body);
$this->assertEquals('**HTML**', $body->getParts()[0]->bodyToString());
$this->assertEquals(str_replace(['=', "\n"], ['=3D', "\r\n"], $html), $body->getParts()[1]->bodyToString());
}

public function testRenderMultiLineHtmlOnly()
Expand All @@ -50,7 +62,7 @@ public function testRenderMultiLineHtmlOnly()
$email = $this->prepareEmail(null, $html);
$body = $email->getBody();
$this->assertInstanceOf(AlternativePart::class, $body);
$this->assertEquals('HTML', str_replace(["\r", "\n"], '', $body->getParts()[0]->bodyToString()));
$this->assertEquals('**HTML**', str_replace(["\r", "\n"], '', $body->getParts()[0]->bodyToString()));
$this->assertEquals(str_replace(['=', "\n"], ['=3D', "\r\n"], $html), $body->getParts()[1]->bodyToString());
}

Expand Down Expand Up @@ -121,15 +133,15 @@ public function testRenderedOnceUnserializableContext()
$this->assertEquals('Text', $email->getTextBody());
}

private function prepareEmail(?string $text, ?string $html, array $context = []): TemplatedEmail
private function prepareEmail(?string $text, ?string $html, array $context = [], HtmlToTextConverterInterface $converter = null): TemplatedEmail
{
$twig = new Environment(new ArrayLoader([
'text' => $text,
'html' => $html,
'document.txt' => 'Some text document...',
'image.jpg' => 'Some image data',
]));
$renderer = new BodyRenderer($twig);
$renderer = new BodyRenderer($twig, [], $converter);
$email = (new TemplatedEmail())
->to('fabien@symfony.com')
->from('helene@symfony.com')
Expand Down
4 changes: 3 additions & 1 deletion src/Symfony/Bridge/Twig/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
"require-dev": {
"doctrine/annotations": "^1.12",
"egulias/email-validator": "^2.1.10|^3",
"league/html-to-markdown": "^5.0",
"phpdocumentor/reflection-docblock": "^3.0|^4.0|^5.0",
"symfony/asset": "^5.4|^6.0",
"symfony/dependency-injection": "^5.4|^6.0",
Expand All @@ -32,7 +33,7 @@
"symfony/http-foundation": "^5.4|^6.0",
"symfony/http-kernel": "^6.2",
"symfony/intl": "^5.4|^6.0",
"symfony/mime": "^5.4|^6.0",
"symfony/mime": "^6.2",
"symfony/polyfill-intl-icu": "~1.0",
"symfony/property-info": "^5.4|^6.0",
"symfony/routing": "^5.4|^6.0",
Expand All @@ -59,6 +60,7 @@
"symfony/form": "<6.1",
"symfony/http-foundation": "<5.4",
"symfony/http-kernel": "<6.2",
"symfony/mime": "<6.2",
"symfony/translation": "<5.4",
"symfony/workflow": "<5.4"
},
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Mime\HtmlToTextConverter;

/**
* @author Fabien Potencier <fabien@symfony.com>
*/
class DefaultHtmlToTextConverter implements HtmlToTextConverterInterface
{
public function convert(string $html, string $charset): string
{
return strip_tags(preg_replace('{<(head|style)\b.*?</\1>}is', '', $html));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Mime\HtmlToTextConverter;

/**
* @author Fabien Potencier <fabien@symfony.com>
*/
interface HtmlToTextConverterInterface
{
/**
* Converts and HTML representation of a Message to a text representation.
*
* The output must use the same charset as the HTML one.
*/
public function convert(string $html, string $charset): string;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Mime\HtmlToTextConverter;

use League\HTMLToMarkdown\HtmlConverter;
use League\HTMLToMarkdown\HtmlConverterInterface;

/**
* @author Fabien Potencier <fabien@symfony.com>
*/
class LeagueHtmlToMarkdownConverter implements HtmlToTextConverterInterface
{
public function __construct(
private HtmlConverterInterface $converter = new HtmlConverter([
'hard_break' => true,
'strip_tags' => true,
'remove_nodes' => 'head style',
]),
) {
}

public function convert(string $html, string $charset): string
{
return $this->converter->convert($html);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Mime\Tests\HtmlToTextConverter;

use PHPUnit\Framework\TestCase;
use Symfony\Component\Mime\HtmlToTextConverter\DefaultHtmlToTextConverter;

class DefaultHtmlToTextConverterTest extends TestCase
{
public function testConvert()
{
$converter = new DefaultHtmlToTextConverter();
$this->assertSame('HTML', $converter->convert('<head><meta charset="utf-8"></head><b>HTML</b><style>css</style>', 'UTF-8'));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Mime\Tests\HtmlToTextConverter;

use PHPUnit\Framework\TestCase;
use Symfony\Component\Mime\HtmlToTextConverter\LeagueHtmlToMarkdownConverter;

class LeagueHtmlToMarkdownConverterTest extends TestCase
{
public function testConvert()
{
$converter = new LeagueHtmlToMarkdownConverter();
$this->assertSame('**HTML**', $converter->convert('<head><meta charset="utf-8"></head><b>HTML</b><style>css</style>', 'UTF-8'));
}
}
1 change: 1 addition & 0 deletions src/Symfony/Component/Mime/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
},
"require-dev": {
"egulias/email-validator": "^2.1.10|^3.1",
"league/html-to-markdown": "^5.0",
"phpdocumentor/reflection-docblock": "^3.0|^4.0|^5.0",
"symfony/dependency-injection": "^5.4|^6.0",
"symfony/property-access": "^5.4|^6.0",
Expand Down