Implement markdown link replacement with snip url
This commit is contained in:
parent
c1b896a63a
commit
d7e558cae9
@ -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));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -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) {
|
||||
|
Loading…
x
Reference in New Issue
Block a user