-
Notifications
You must be signed in to change notification settings - Fork 5
/
Extension.php
109 lines (96 loc) · 2.88 KB
/
Extension.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
<?php
/**
* ToC Extension/Plugin for Parsedown.
*
* It creates a list of contents table from headings.
*
* @version 20180407-2203
* @author KEINOS (https://github.com/KEINOS/)
* @package Parsedown 1.7.1 (https://github.com/erusev/parsedown)
* @see Howto: https://github.com/KEINOS/parsedown-extension_table-of-contents/
* @license https://github.com/KEINOS/parsedown-extension_table-of-contents/LICENSE
*/
class Extension extends Parsedown
{
protected function fetchText($Text)
{
return trim(strip_tags($this->line($Text)));
}
protected function createAnchorID($Text)
{
return urlencode($this->fetchText($Text));
}
#
# contents list
#
function contentsList($Return_as = 'string')
{
if ('string' === strtolower($Return_as)) {
$result = '';
if (! empty($this->contentsListString)) {
$result = $this->text($this->contentsListString);
}
return $result;
} elseif ('json' === strtolower($Return_as)) {
return json_encode($this->contentsListArray);
} else {
return $this->contentsListArray;
}
}
#
# Setters
#
protected function setContentsList($Content)
{
$this->setContentsListAsArray($Content);
$this->setContentsListAsString($Content);
}
protected function setContentsListAsArray($Content)
{
$this->contentsListArray[] = $Content;
}
protected $contentsListArray = array();
protected function setContentsListAsString($Content)
{
$text = $this->fetchText($Content['text']);
$id = $Content['id'];
$level = (integer) trim($Content['level'], 'h');
$link = "[${text}](#${id})";
if ($this->firstHeadLevel === 0) {
$this->firstHeadLevel = $level;
}
$cutIndent = $this->firstHeadLevel - 1;
if ($cutIndent > $level) {
$level = 1;
} else {
$level = $level - $cutIndent;
}
$indent = str_repeat(' ', $level);
$this->contentsListString .= "${indent}- ${link}\n";
}
protected $contentsListString = '';
protected $firstHeadLevel = 0;
#
# Header
#
protected function blockHeader($Line)
{
if (isset($Line['text'][1])) {
$Block = Parsedown::blockHeader($Line);
$text = $Block['element']['handler']['argument'];
$level = $Block['element']['name']; //h1,h2..h6
$id = $this->createAnchorID($text);
//Set attributes to head tags
$Block['element']['attributes'] = [
'id' => $id,
'name' => $id,
];
$this->setContentsList([
'text' => $text,
'id' => $id,
'level' => $level
]);
return $Block;
}
}
}