Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A Custom Markdown Parser for Jigsaw projects.
<?php
namespace App\Markdown;
use Illuminate\Container\Container;
use League\CommonMark\Block\Element\FencedCode;
use League\CommonMark\Block\Element\IndentedCode;
use League\CommonMark\CommonMarkConverter;
use League\CommonMark\Environment;
use League\CommonMark\Extension\ExternalLink\ExternalLinkExtension;
use Spatie\CommonMarkHighlighter\FencedCodeRenderer;
use Spatie\CommonMarkHighlighter\IndentedCodeRenderer;
use TightenCo\Jigsaw\Parsers\MarkdownParser;
class CustomParser extends MarkdownParser
{
protected static array $languages = [
'html', 'php', 'js', 'css',
];
protected CommonMarkConverter $commonmark;
protected Container $container;
public function __construct()
{
parent::__construct();
$this->container = Container::getInstance();
$this->commonmark = $this->createCommonmark();
}
protected function createCommonmark(): CommonMarkConverter
{
$environment = Environment::createCommonMarkEnvironment();
if ($this->container->config['production']) {
$environment->addBlockRenderer(FencedCode::class, new FencedCodeRenderer(static::$languages));
$environment->addBlockRenderer(IndentedCode::class, new IndentedCodeRenderer(static::$languages));
}
$environment->addExtension(new ExternalLinkExtension());
$config = [
'external_link' => [
'internal_hosts' => 'stefanzweifel.io',
'open_in_new_window' => true,
'html_class' => 'external-link',
],
];
return new CommonMarkConverter($config, $environment);
}
public function parse($markdown): string
{
return $this->commonmark->convertToHtml($markdown);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment