Implement MarkDown parser and improve AbstractParser

This commit is contained in:
Tim
2025-04-23 21:50:50 +02:00
parent cc3e050304
commit 0f6cc78e5e
9 changed files with 477 additions and 32 deletions

View File

@ -6,11 +6,23 @@ abstract class AbstractParser implements ParserInterface
{
public static function getName(): string
{
return static::class;
$path = explode('\\', static::class);
return strtolower(str_replace('Parser', '', array_pop($path)));
}
public function parseRaw(string $content): string
{
return $content;
}
public function parseView(string $content): string
{
try {
return $this->safeParseView($content);
} catch (\Exception $exception) {
return sprintf('<pre><code class="hljs">%s</code></pre>', htmlspecialchars($exception->getMessage()));
}
}
abstract function safeParseView(string $content): string;
}

View File

@ -7,17 +7,12 @@ use League\Pipeline\PipelineBuilder;
class GenericParser extends AbstractParser
{
public static function getName(): string
{
return 'generic';
}
public function __construct(
private readonly UrlReferenceStage $referenceStage,
private readonly IncludeReferenceStage $includeStage,
) {}
public function parseView(string $content): string
public function safeParseView(string $content): string
{
$builder = new PipelineBuilder();
$pipeline = $builder

View File

@ -1,17 +1,12 @@
<?php
namespace App\Service\SnipParser\Website;
namespace App\Service\SnipParser\Html;
use App\Service\SnipParser\AbstractParser;
class HtmlParser extends AbstractParser
{
public static function getName(): string
{
return 'html';
}
public function parseView(string $content): string
public function safeParseView(string $content): string
{
return sprintf('<pre><code class="hljs">%s</code></pre>', htmlspecialchars($content));
}

View File

@ -0,0 +1,15 @@
<?php
namespace App\Service\SnipParser\Markdown;
use App\Service\SnipParser\AbstractParser;
use League\CommonMark\GithubFlavoredMarkdownConverter;
class MarkdownParser extends AbstractParser
{
public function safeParseView(string $content): string
{
$converter = new GithubFlavoredMarkdownConverter();
return $converter->convert($content);
}
}

View File

@ -13,24 +13,16 @@ class TwigParser extends AbstractParser
private readonly SnipLoader $snipLoader,
) {}
public static function getName(): string
public function safeParseView(string $content): string
{
return 'twig';
}
$loader = new ChainLoader([
new ArrayLoader([
'index' => $content,
]),
$this->snipLoader,
]);
$twig = new Environment($loader);
public function parseView(string $content): string
{
try {
$loader = new ChainLoader([
new ArrayLoader([
'index' => $content,
]),
$this->snipLoader,
]);
$twig = new Environment($loader);
return $twig->render('index');
} catch (\Exception $exception) {
return sprintf('<pre><code class="hljs">%s</code></pre>', htmlspecialchars($exception->getMessage()));
}
return $twig->render('index');
}
}