8
8
9
9
class DocHeader
10
10
{
11
- private string $ title ;
12
- private int $ level ;
13
- private string $ tag ;
14
- private string $ id ;
11
+ /**
12
+ * @var string
13
+ */
14
+ private $ title ;
15
+
16
+ /**
17
+ * @var int
18
+ */
19
+ private $ level ;
20
+
21
+ /**
22
+ * @var string
23
+ */
24
+ private $ tag ;
25
+
26
+ /**
27
+ * @var string
28
+ */
29
+ private $ id ;
15
30
16
31
/**
17
32
* @var DocHeader[]
18
33
*/
19
- private array $ headers = array ();
34
+ private $ headers = array ();
35
+
36
+ /**
37
+ * @var array<string,int>
38
+ */
39
+ private static $ anchors = array ();
40
+
41
+ /**
42
+ * @var string
43
+ */
44
+ private $ anchor ;
20
45
21
46
public function __construct (string $ title , int $ level , string $ matchedTag )
22
47
{
23
48
$ this ->title = $ title ;
24
49
$ this ->level = $ level ;
25
50
$ this ->tag = $ matchedTag ;
26
51
$ this ->id = ConvertHelper::transliterate ($ title );
52
+ $ this ->anchor = $ this ->createAnchor ();
53
+ }
54
+
55
+ private function createAnchor () : string
56
+ {
57
+ if (!isset (self ::$ anchors [$ this ->id ])) {
58
+ self ::$ anchors [$ this ->id ] = 0 ;
59
+ }
60
+
61
+ self ::$ anchors [$ this ->id ]++;
62
+
63
+ $ anchor = $ this ->id ;
64
+
65
+ if (self ::$ anchors [$ this ->id ] > 1 ) {
66
+ $ anchor .= '- ' .self ::$ anchors [$ this ->id ];
67
+ }
68
+
69
+ return $ anchor ;
27
70
}
28
71
29
72
public function addSubheader (DocHeader $ header ) : void
@@ -47,6 +90,11 @@ public function getID(): string
47
90
return $ this ->id ;
48
91
}
49
92
93
+ public function getAnchor () : string
94
+ {
95
+ return $ this ->anchor ;
96
+ }
97
+
50
98
/**
51
99
* @return int
52
100
*/
@@ -77,7 +125,7 @@ public function replace(string $subject, DocFile $file) : string
77
125
sprintf (
78
126
$ template ,
79
127
$ this ->level ,
80
- $ this ->id ,
128
+ $ this ->getAnchor () ,
81
129
$ file ->getID ()
82
130
),
83
131
$ this ->tag
@@ -92,7 +140,7 @@ public function render() : string
92
140
93
141
?>
94
142
<li>
95
- <a href="#<?php echo $ this ->id ?> "><?php echo $ this ->title ?> </a>
143
+ <a href="#<?php echo $ this ->getAnchor () ?> "><?php echo $ this ->title ?> </a>
96
144
<?php echo $ this ->renderSubheaders () ?>
97
145
</li>
98
146
<?php
0 commit comments