Created
April 15, 2021 18:18
-
-
Save stefanzweifel/b16ae32e5829ae9605d2e94c62e04de1 to your computer and use it in GitHub Desktop.
A Custom Markdown Parser for Jigsaw projects.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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