Renderer: Added twig extension for markdown rendering
parent
b3f059ad04
commit
393db49294
@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
namespace Engelsystem\Renderer\Twig\Extensions;
|
||||
|
||||
use Parsedown;
|
||||
use Twig_Extension as TwigExtension;
|
||||
use Twig_Filter as TwigFilter;
|
||||
|
||||
class Markdown extends TwigExtension
|
||||
{
|
||||
/** @var Parsedown */
|
||||
protected $renderer;
|
||||
|
||||
/**
|
||||
* @param Parsedown $renderer
|
||||
*/
|
||||
public function __construct(Parsedown $renderer)
|
||||
{
|
||||
$this->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));
|
||||
}
|
||||
}
|
@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
namespace Engelsystem\Test\Unit\Renderer\Twig\Extensions;
|
||||
|
||||
use Engelsystem\Renderer\Twig\Extensions\Markdown;
|
||||
use Parsedown;
|
||||
use PHPUnit\Framework\MockObject\MockObject;
|
||||
|
||||
class MarkdownTest extends ExtensionTest
|
||||
{
|
||||
/**
|
||||
* @covers \Engelsystem\Renderer\Twig\Extensions\Markdown::getFilters
|
||||
*/
|
||||
public function testGeFilters()
|
||||
{
|
||||
/** @var Parsedown|MockObject $renderer */
|
||||
$renderer = $this->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 = '<p>Lorem <em>"Ipsum"</em></p>';
|
||||
$renderer->expects($this->once())
|
||||
->method('text')
|
||||
->with('Lorem *"Ipsum"*')
|
||||
->willReturn($return);
|
||||
|
||||
$extension = new Markdown($renderer);
|
||||
$this->assertEquals($return, $extension->render('Lorem *"Ipsum"*'));
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue