From d7e558cae9a635f4397ad765b505d63affa2109c Mon Sep 17 00:00:00 2001 From: Tim Date: Thu, 24 Apr 2025 18:16:44 +0200 Subject: [PATCH] Implement markdown link replacement with snip url --- .../SnipParser/Markdown/MarkdownParser.php | 38 +++++++++++++++++++ .../SnipParser/Twig/SnipTwigExtension.php | 4 +- 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/src/Service/SnipParser/Markdown/MarkdownParser.php b/src/Service/SnipParser/Markdown/MarkdownParser.php index 476c629..eb603ce 100644 --- a/src/Service/SnipParser/Markdown/MarkdownParser.php +++ b/src/Service/SnipParser/Markdown/MarkdownParser.php @@ -2,14 +2,52 @@ namespace App\Service\SnipParser\Markdown; +use App\Repository\SnipRepository; use App\Service\SnipParser\AbstractParser; +use League\CommonMark\Event\DocumentParsedEvent; +use League\CommonMark\Extension\CommonMark\Node\Inline\Link; use League\CommonMark\GithubFlavoredMarkdownConverter; +use League\CommonMark\Node\Inline\Text; +use League\CommonMark\Node\Query; +use Symfony\Component\DependencyInjection\Attribute\Autowire; +use Symfony\Component\Routing\RouterInterface; class MarkdownParser extends AbstractParser { + public function __construct( + #[Autowire(lazy: true)] private readonly RouterInterface $router, + #[Autowire(lazy: true)] private readonly SnipRepository $snipRepo, + ) {} + public function safeParseView(string $content): string { $converter = new GithubFlavoredMarkdownConverter(); + $converter->getEnvironment()->addEventListener(DocumentParsedEvent::class, $this->documentParsed(...)); return $converter->convert($content); } + + private function documentParsed(DocumentParsedEvent $event): void + { + $document = $event->getDocument(); + + $linkNodes = new Query() + ->where(Query::type(Link::class)) + ->findAll($document); + + foreach ($linkNodes as $linkNode) { + $url = $linkNode->getUrl(); + + $snip = $this->snipRepo->find($url); + if ($snip === null) { + continue; + } + $linkNode->setUrl($this->router->generate('snip_single', [ + 'snip' => $url, + ])); + $textNode = $linkNode->firstChild(); + if (!$textNode) { + $linkNode->appendChild(new Text($snip)); + } + } + } } \ No newline at end of file diff --git a/src/Service/SnipParser/Twig/SnipTwigExtension.php b/src/Service/SnipParser/Twig/SnipTwigExtension.php index 3bf154f..2485bcf 100644 --- a/src/Service/SnipParser/Twig/SnipTwigExtension.php +++ b/src/Service/SnipParser/Twig/SnipTwigExtension.php @@ -25,14 +25,14 @@ class SnipTwigExtension extends AbstractExtension ]; } - function snipPath(int $id): string + private function snipPath(int $id): string { return $this->router->generate('snip_single', [ 'snip' => $id, ]); } - function snipLink(int $id): string + private function snipLink(int $id): string { $snip = $this->snipRepo->find($id); if ($snip === null) {