Skip to content

Commit 8ac4b0b

Browse files
committed
Added getAnchor(), fixed duplicate anchor issues.
1 parent 1902067 commit 8ac4b0b

File tree

1 file changed

+55
-7
lines changed

1 file changed

+55
-7
lines changed

src/DocHeader.php

Lines changed: 55 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,22 +8,65 @@
88

99
class DocHeader
1010
{
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;
1530

1631
/**
1732
* @var DocHeader[]
1833
*/
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;
2045

2146
public function __construct(string $title, int $level, string $matchedTag)
2247
{
2348
$this->title = $title;
2449
$this->level = $level;
2550
$this->tag = $matchedTag;
2651
$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;
2770
}
2871

2972
public function addSubheader(DocHeader $header) : void
@@ -47,6 +90,11 @@ public function getID(): string
4790
return $this->id;
4891
}
4992

93+
public function getAnchor() : string
94+
{
95+
return $this->anchor;
96+
}
97+
5098
/**
5199
* @return int
52100
*/
@@ -77,7 +125,7 @@ public function replace(string $subject, DocFile $file) : string
77125
sprintf(
78126
$template,
79127
$this->level,
80-
$this->id,
128+
$this->getAnchor(),
81129
$file->getID()
82130
),
83131
$this->tag
@@ -92,7 +140,7 @@ public function render() : string
92140

93141
?>
94142
<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>
96144
<?php echo $this->renderSubheaders() ?>
97145
</li>
98146
<?php

0 commit comments

Comments
 (0)