forked from typecho-fans/plugins
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ParsedownExtension.php
75 lines (56 loc) · 1.9 KB
/
ParsedownExtension.php
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
<?php
require_once 'Parsedown.php';
class ParsedownExtension extends Parsedown
{
protected $isTocEnabled = false;
protected $absoluteUrl = '';
protected $rawTocList = [];
protected $findTocSyntaxRule = '#^<p> *\[TOC\]\s*</p>$#m';
public function setTocEnabled($isTocEnable)
{
$this->isTocEnabled = $isTocEnable;
return $this;
}
public function setTocSyntaxRule($findTocSyntaxRule)
{
$this->findTocSyntaxRule = $findTocSyntaxRule;
return $this;
}
public function setAbsoluteUrl($absoluteUrl)
{
$this->absoluteUrl = $absoluteUrl;
return $this;
}
public function text($text)
{
$content = parent::text($text);
if (!$this->isTocEnabled || empty($this->rawTocList) || !preg_match($this->findTocSyntaxRule, $content)) {
return $content;
}
return preg_replace($this->findTocSyntaxRule, $this->buildToc(), $content);
}
protected function buildToc()
{
$tocMarkdownContent = '';
$topHeadLevel = min(array_column($this->rawTocList, 'level'));
foreach ($this->rawTocList as $id => $tocItem) {
$tocMarkdownContent .= sprintf('%s- [%s](%s#%s)' . PHP_EOL, str_repeat(' ', $tocItem['level'] - $topHeadLevel), $this->line($tocItem['text']), $this->absoluteUrl, $id);
}
$this->rawTocList = [];
return parent::text($tocMarkdownContent);
}
protected function blockHeader($line)
{
$block = parent::blockHeader($line);
$text = $block['element']['handler']['argument'];
$id = urlencode($this->line($text));
$block['element']['attributes'] = [
'id' => $id,
];
$this->rawTocList[$id] = [
'text' => $text,
'level' => str_replace('h', '', $block['element']['name']),
];
return $block;
}
}