Skip to content

Commit d475265

Browse files
[2.x] Commonmark grammar fallback (#116)
* Fallback to txt when grammar does not exist in CommonMark extension * Use the Grammar enum instead of magic string
1 parent 0a8ea64 commit d475265

File tree

3 files changed

+25
-1
lines changed

3 files changed

+25
-1
lines changed

src/Adapters/CommonMark/CodeBlockRenderer.php

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,11 +41,15 @@ public function render(Node $node, ChildNodeRendererInterface $childRenderer)
4141
protected function detectGrammar(FencedCode $node): Grammar|string
4242
{
4343
if (! isset($node->getInfoWords()[0]) || $node->getInfoWords()[0] === '') {
44-
return 'txt';
44+
return Grammar::Txt;
4545
}
4646

4747
preg_match('/[a-zA-Z]+/', $node->getInfoWords()[0], $matches);
4848

49+
if (! $this->phiki->environment->grammars->has($matches[0])) {
50+
return Grammar::Txt;
51+
}
52+
4953
return $matches[0];
5054
}
5155
}
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
<pre class="phiki github-dark" style="background-color: #24292e;color: #e1e4e8;"><code><span class="line"><span class="token">class A {}
2+
</span></span></code></pre>

tests/Adapters/CommonMark/PhikiExtensionTest.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,3 +65,21 @@ class A {}
6565

6666
expect($generated)->toMatchSnapshot();
6767
});
68+
69+
it('falls back to txt if the grammar doesnt exist', function () {
70+
$environment = new Environment;
71+
72+
$environment
73+
->addExtension(new CommonMarkCoreExtension)
74+
->addExtension(new PhikiExtension('github-dark'));
75+
76+
$markdown = new MarkdownConverter($environment);
77+
78+
$generated = $markdown->convert(<<<'MD'
79+
```nonexistentlang
80+
class A {}
81+
```
82+
MD);
83+
84+
expect($generated)->toMatchSnapshot();
85+
});

0 commit comments

Comments
 (0)