From 9b64af120d24e1620c528e0a04fc434a2ea39943 Mon Sep 17 00:00:00 2001 From: TJ Miller Date: Wed, 20 May 2020 11:01:26 -0400 Subject: [PATCH] Adds support for parsedown extra (#10) --- README.md | 10 +++++++ composer.json | 3 +- src/ParsedownHighlightExtra.php | 42 +++++++++++++++++++++++++++ tests/ParsedownExtraHighlightTest.php | 29 ++++++++++++++++++ 4 files changed, 83 insertions(+), 1 deletion(-) create mode 100644 src/ParsedownHighlightExtra.php create mode 100644 tests/ParsedownExtraHighlightTest.php diff --git a/README.md b/README.md index 35c288b..e7c16de 100644 --- a/README.md +++ b/README.md @@ -51,6 +51,16 @@ $parsedown->text(file_get_contents(__DIR__.'/README.md'));
put 'WHOOP!'
``` +### Using Parsedown Extra +**Note: This requires version [0.8.0-beta-1](https://github.com/erusev/parsedown-extra/releases/tag/0.8.0-beta-1)** + +```php +$parsedown = new \sixlive\ParsedownHighlightExtra; + +$parsedown->text(file_get_contents(__DIR__.'/README.md')); +``` + + ## Testing ``` bash diff --git a/composer.json b/composer.json index b1f47db..75150a8 100644 --- a/composer.json +++ b/composer.json @@ -19,7 +19,8 @@ "require": { "php": "^7.1|7.2", "erusev/parsedown": "1.8.0-beta-5", - "scrivo/highlight.php": "^9.14" + "scrivo/highlight.php": "^9.14", + "erusev/parsedown-extra": "0.8.0-beta-1" }, "require-dev": { "friendsofphp/php-cs-fixer": "^2.10", diff --git a/src/ParsedownHighlightExtra.php b/src/ParsedownHighlightExtra.php new file mode 100644 index 0000000..5b46d46 --- /dev/null +++ b/src/ParsedownHighlightExtra.php @@ -0,0 +1,42 @@ +highlighter = new Highlighter; + } + + protected function blockFencedCodeComplete($block) + { + if (! isset($block['element']['element']['attributes'])) { + return $block; + } + + $code = $block['element']['element']['text']; + $languageClass = $block['element']['element']['attributes']['class']; + $language = explode('-', $languageClass); + + try { + $highlighted = $this->highlighter->highlight($language[1], $code); + $block['element']['element']['attributes']['class'] = vsprintf('%s hljs %s', [ + $languageClass, + $highlighted->language, + ]); + $block['element']['element']['rawHtml'] = $highlighted->value; + unset($block['element']['element']['text']); + } catch (DomainException $e) { + // + } + + return $block; + } +} diff --git a/tests/ParsedownExtraHighlightTest.php b/tests/ParsedownExtraHighlightTest.php new file mode 100644 index 0000000..175c765 --- /dev/null +++ b/tests/ParsedownExtraHighlightTest.php @@ -0,0 +1,29 @@ +text(file_get_contents(__DIR__.'/Support/test.md')); + + $this->assertContains("
<?php\n\necho 'foo';
", $renderedMarkdown); + } + + /** @test */ + public function language_errors_are_swallowd() + { + $parsedown = new ParsedownHighlightExtra; + + $renderedMarkdown = $parsedown->text(file_get_contents(__DIR__.'/Support/test.md')); + + $this->assertContains("
put 'WHOOP!'
", $renderedMarkdown); + } +}