findMinLevel($headings);
return $this->buildRecursive($headings, 0, $min_level);
}
private function findMinLevel(array $headings): int {
$levels = array_column($headings, 'level');
return !empty($levels) ? min($levels) : 1;
}
private function buildRecursive(array $headings, int $index, int $current_level): string {
$html = '
';
$count = count($headings);
while ($index < $count) {
$heading = $headings[$index];
if ($heading['level'] < $current_level) {
break;
}
if ($heading['level'] === $current_level) {
$html .= sprintf(
'- %s',
esc_attr($heading['level']),
esc_attr($heading['anchor']),
esc_html($heading['clean_text'])
);
$index++;
if ($index < $count && $headings[$index]['level'] > $current_level) {
$nested_html = $this->buildRecursive($headings, $index, $current_level + 1);
$html .= $nested_html;
while ($index < $count && $headings[$index]['level'] > $current_level) {
$index++;
}
}
$html .= '
';
continue;
}
if ($heading['level'] > $current_level) {
$nested_html = $this->buildRecursive($headings, $index, $current_level + 1);
$html .= $nested_html;
while ($index < $count && $headings[$index]['level'] >= $current_level + 1) {
$index++;
}
}
}
$html .= '
';
return $html;
}
}