From 9db87731508a4e8c0e0f6a91d66ee5293a482b01 Mon Sep 17 00:00:00 2001 From: Tobias Wiese Date: Wed, 29 Dec 2021 17:14:11 +0100 Subject: [PATCH] markdown: let Parsedown escape content Letting Parsedown escape the content, instead of calling htmlspecialchars provides more context to the escape process. For example the ampersand character can now be used in markdown links as part of the url without breaking. --- src/Renderer/Twig/Extensions/Markdown.php | 6 +-- .../Renderer/Twig/Extensions/MarkdownTest.php | 37 ++++++------------- 2 files changed, 13 insertions(+), 30 deletions(-) diff --git a/src/Renderer/Twig/Extensions/Markdown.php b/src/Renderer/Twig/Extensions/Markdown.php index 3e390796..0744dae4 100644 --- a/src/Renderer/Twig/Extensions/Markdown.php +++ b/src/Renderer/Twig/Extensions/Markdown.php @@ -40,10 +40,6 @@ class Markdown extends TwigExtension */ public function render(string $text, bool $escapeHtml = true): string { - if ($escapeHtml) { - $text = htmlspecialchars($text); - } - - return $this->renderer->text($text); + return $this->renderer->setSafeMode($escapeHtml)->text($text); } } diff --git a/tests/Unit/Renderer/Twig/Extensions/MarkdownTest.php b/tests/Unit/Renderer/Twig/Extensions/MarkdownTest.php index 70eea97c..5a1b01c0 100644 --- a/tests/Unit/Renderer/Twig/Extensions/MarkdownTest.php +++ b/tests/Unit/Renderer/Twig/Extensions/MarkdownTest.php @@ -13,10 +13,7 @@ class MarkdownTest extends ExtensionTest */ public function testGeFilters() { - /** @var Parsedown|MockObject $renderer */ - $renderer = $this->createMock(Parsedown::class); - - $extension = new Markdown($renderer); + $extension = new Markdown(new Parsedown()); $filters = $extension->getFilters(); $this->assertExtensionExists('markdown', [$extension, 'render'], $filters); @@ -29,17 +26,12 @@ class MarkdownTest extends ExtensionTest */ public function testRender() { - /** @var Parsedown|MockObject $renderer */ - $renderer = $this->createMock(Parsedown::class); + $extension = new Markdown(new Parsedown()); - $return = '

Lorem "Ipsum"

'; - $renderer->expects($this->once()) - ->method('text') - ->with('Lorem *"Ipsum"*') - ->willReturn($return); - - $extension = new Markdown($renderer); - $this->assertEquals($return, $extension->render('Lorem *"Ipsum"*')); + $this->assertEquals( + '

<i>Lorem</i> "Ipsum"

', + $extension->render('Lorem *"Ipsum"*'), + ); } /** @@ -47,17 +39,12 @@ class MarkdownTest extends ExtensionTest */ public function testRenderHtml() { - /** @var Parsedown|MockObject $renderer */ - $renderer = $this->createMock(Parsedown::class); - - $input = '**test**'; - $return = '

**test**

'; - $renderer->expects($this->once()) - ->method('text') - ->with($input) - ->willReturn($return); - + $renderer = new Parsedown(); $extension = new Markdown($renderer); - $this->assertEquals($return, $extension->render($input, false)); + + $this->assertEquals( + '

Lorem "Ipsum"

', + $extension->render('Lorem *"Ipsum"*', false), + ); } }