-
-
Notifications
You must be signed in to change notification settings - Fork 122
Expand file tree
/
Copy pathTwigMarkdownTOCExtension.php
More file actions
50 lines (42 loc) · 1.44 KB
/
TwigMarkdownTOCExtension.php
File metadata and controls
50 lines (42 loc) · 1.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<?php
namespace Fig\Website;
use League\CommonMark\DocParser;
use League\CommonMark\DocParserInterface;
use League\CommonMark\ElementRendererInterface;
use League\CommonMark\EnvironmentInterface;
use League\CommonMark\Extension\TableOfContents\TableOfContentsGenerator;
use League\CommonMark\HtmlRenderer;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
class TwigMarkdownTOCExtension extends AbstractExtension
{
private readonly DocParserInterface $docParser;
private readonly ElementRendererInterface $htmlRenderer;
public function __construct(
EnvironmentInterface $environment,
) {
$this->docParser = new DocParser($environment);
$this->htmlRenderer = new HtmlRenderer($environment);
}
public function getFilters()
{
return [
new TwigFilter('markdown_toc', function(string $markdown): string {
return $this->renderTOC($markdown);
}),
];
}
private function renderTOC(string $markdown): string
{
$generator = new TableOfContentsGenerator(
TableOfContentsGenerator::STYLE_ORDERED,
TableOfContentsGenerator::NORMALIZE_RELATIVE,
minHeadingLevel: 2,
maxHeadingLevel: 3,
);
$toc = $generator->generate($this->docParser->parse($markdown));
return $toc === null
? ''
: $this->htmlRenderer->renderBlock($toc, inTightList: true);
}
}