Implement markdown link replacement with snip url

This commit is contained in:
Tim 2025-04-24 18:16:44 +02:00
parent c1b896a63a
commit d7e558cae9
2 changed files with 40 additions and 2 deletions

View File

@ -2,14 +2,52 @@
namespace App\Service\SnipParser\Markdown; namespace App\Service\SnipParser\Markdown;
use App\Repository\SnipRepository;
use App\Service\SnipParser\AbstractParser; 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\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 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 public function safeParseView(string $content): string
{ {
$converter = new GithubFlavoredMarkdownConverter(); $converter = new GithubFlavoredMarkdownConverter();
$converter->getEnvironment()->addEventListener(DocumentParsedEvent::class, $this->documentParsed(...));
return $converter->convert($content); 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));
}
}
}
} }

View File

@ -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', [ return $this->router->generate('snip_single', [
'snip' => $id, 'snip' => $id,
]); ]);
} }
function snipLink(int $id): string private function snipLink(int $id): string
{ {
$snip = $this->snipRepo->find($id); $snip = $this->snipRepo->find($id);
if ($snip === null) { if ($snip === null) {