diff --git a/src/Renderer/Twig/Extensions/Markdown.php b/src/Renderer/Twig/Extensions/Markdown.php new file mode 100644 index 00000000..293efe91 --- /dev/null +++ b/src/Renderer/Twig/Extensions/Markdown.php @@ -0,0 +1,43 @@ +renderer = $renderer; + } + + /** + * @return array + */ + public function getFilters(): array + { + $options = ['is_safe' => ['html']]; + + return [ + new TwigFilter('markdown', [$this, 'render'], $options), + new TwigFilter('md', [$this, 'render'], $options), + ]; + } + + /** + * @param string $text + * @return string + */ + public function render($text): string + { + return $this->renderer->text(htmlspecialchars($text)); + } +} diff --git a/src/Renderer/TwigServiceProvider.php b/src/Renderer/TwigServiceProvider.php index d7b6bd09..6cd885fd 100644 --- a/src/Renderer/TwigServiceProvider.php +++ b/src/Renderer/TwigServiceProvider.php @@ -10,6 +10,7 @@ use Engelsystem\Renderer\Twig\Extensions\Config; use Engelsystem\Renderer\Twig\Extensions\Csrf; use Engelsystem\Renderer\Twig\Extensions\Globals; use Engelsystem\Renderer\Twig\Extensions\Legacy; +use Engelsystem\Renderer\Twig\Extensions\Markdown; use Engelsystem\Renderer\Twig\Extensions\Session; use Engelsystem\Renderer\Twig\Extensions\Translation; use Engelsystem\Renderer\Twig\Extensions\Url; @@ -28,6 +29,7 @@ class TwigServiceProvider extends ServiceProvider 'globals' => Globals::class, 'session' => Session::class, 'legacy' => Legacy::class, + 'markdown' => Markdown::class, 'translation' => Translation::class, 'url' => Url::class, ]; diff --git a/tests/Unit/Renderer/Twig/Extensions/MarkdownTest.php b/tests/Unit/Renderer/Twig/Extensions/MarkdownTest.php new file mode 100644 index 00000000..fd98c7cd --- /dev/null +++ b/tests/Unit/Renderer/Twig/Extensions/MarkdownTest.php @@ -0,0 +1,44 @@ +createMock(Parsedown::class); + + $extension = new Markdown($renderer); + $filters = $extension->getFilters(); + + $this->assertExtensionExists('markdown', [$extension, 'render'], $filters); + $this->assertExtensionExists('md', [$extension, 'render'], $filters); + } + + /** + * @covers \Engelsystem\Renderer\Twig\Extensions\Markdown::__construct + * @covers \Engelsystem\Renderer\Twig\Extensions\Markdown::render + */ + public function testRender() + { + /** @var Parsedown|MockObject $renderer */ + $renderer = $this->createMock(Parsedown::class); + + $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"*')); + } +}