1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Marquage\ParsedownAnchors; |
4
|
|
|
|
5
|
|
|
use ParsedownExtra; |
6
|
|
|
use Cocur\Slugify\Slugify; |
7
|
|
|
|
8
|
|
|
class ParsedownSlugified extends ParsedownExtra |
9
|
|
|
{ |
10
|
|
|
protected $used = []; |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* Overrides both Parsedown & Parsedown-extra to capture parsed headers, add a unique slug-id to each for the output |
14
|
|
|
* @param $Line |
15
|
|
|
* @return array|void |
16
|
|
|
*/ |
17
|
|
|
protected function blockHeader($Line) |
18
|
|
|
{ |
19
|
|
|
$Block = []; |
20
|
|
|
if (isset($Line['text'][1])) { |
21
|
|
|
$level = 1; |
22
|
|
|
|
23
|
|
|
while (isset($Line['text'][$level]) and $Line['text'][$level] === '#') { |
24
|
|
|
if ($level < 7) { |
25
|
|
|
$level++; |
26
|
|
|
} |
27
|
|
|
} |
28
|
|
|
$text = trim($Line['text'], '# '); |
29
|
|
|
|
30
|
|
|
$Block = array( |
31
|
|
|
'element' => [ |
32
|
|
|
'name' => 'h' . min(6, $level), |
33
|
|
|
'text' => $text, |
34
|
|
|
'handler' => 'line', |
35
|
|
|
'attributes' => [ |
36
|
|
|
'id' => $this->slugify($text) |
37
|
|
|
] |
38
|
|
|
], |
39
|
|
|
); |
40
|
|
|
} |
41
|
|
|
if (preg_match( |
42
|
|
|
'/[ #]*{(' . $this->regexAttribute . '+)}[ ]*$/', |
43
|
|
|
$Block['element']['text'], |
44
|
|
|
$matches, |
45
|
|
|
PREG_OFFSET_CAPTURE |
46
|
|
|
)) { |
47
|
|
|
$attributeString = $matches[1][0]; |
48
|
|
|
$Block['element']['attributes'] = $this->parseAttributeData($attributeString); |
49
|
|
|
$Block['element']['text'] = substr($Block['element']['text'], 0, $matches[0][1]); |
50
|
|
|
} |
51
|
|
|
return $Block; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* Uses Cocur to slugify but ensures each slug is unique |
56
|
|
|
* credit: https://github.com/caseyamcl/toc |
57
|
|
|
* @param $text |
58
|
|
|
* @return string |
59
|
|
|
*/ |
60
|
|
|
protected function slugify($text) |
61
|
|
|
{ |
62
|
|
|
$slugger = new Slugify(); |
63
|
|
|
$slugged = $slugger->slugify($text); |
64
|
|
|
$count = 1; |
65
|
|
|
$orig = $slugged; |
66
|
|
|
while (in_array($slugged, $this->used)) { |
67
|
|
|
$slugged = $orig . '-' . $count; |
68
|
|
|
$count++; |
69
|
|
|
} |
70
|
|
|
$this->used[] = $slugged; |
71
|
|
|
return $slugged; |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|