Skip to content

Instantly share code, notes, and snippets.

@stefanzweifel
Created April 15, 2021 18:18
Show Gist options
  • Save stefanzweifel/b16ae32e5829ae9605d2e94c62e04de1 to your computer and use it in GitHub Desktop.
Save stefanzweifel/b16ae32e5829ae9605d2e94c62e04de1 to your computer and use it in GitHub Desktop.
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