<?php
namespace App\Controller;
use Parsedown;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use voku\helper\HtmlDomParser;
class SidebarController extends AbstractController
{
#[Route('/sidebar', name: 'app_sidebar')]
public function index(): Response
{
$filePathSidebar = $this->getParameter('kernel.project_dir') . "/mxo-docs/_sidebar.md";
$filesystem = new Filesystem();
$links = array();
if ($filesystem->exists($filePathSidebar)) {
$links = $this->parseSidebar($filePathSidebar);
}
return $this->render('sidebar/_menu_entries.html.twig', [
'menuEntries' => $links
]);
}
function parseSidebar($file)
{
// Datei in String laden
$content = file_get_contents($file);
// Markdown-Parser initialisieren
$parser = new Parsedown();
// Markdown in HTML parsen
$html = $parser->text($content);
$html = "<div>" . $html . "</div>";
$html = str_replace('<div><ul>','<div><ul class="first">', $html);
$dom = HtmlDomParser::str_get_html($html);
// HTML-Elemente in Array konvertieren
$elements = $dom->find('ul.first > li');
// Sidebar-Array initialisieren
$sidebar = array();
foreach ($elements as $item) {
$link = $item->find('a')[0]->getAttribute('href');
$text = $item->find('a')[0]->textContent;
// Sublinks parsen
$sublinks = array();
$subitems = $item->find('ul li a');#
if ($subitems->count() > 0) {
foreach ($subitems as $subitem) {
$sublinks[] = array(
'link' => ltrim($subitem->find('a')[0]->getAttribute('href'), '.'),
'text' => trim($subitem->find('a')[0]->textContent),
);
}
}
if(count($sublinks)>0){
$sublinks = array_unique($sublinks, SORT_REGULAR);
}
$sidebar[] = array(
'link' => ltrim($link, '.'),
'text' => trim($text),
'sublinks' => $sublinks,
);
}
// Sidebar-Array zurückgeben
return array_unique($sidebar, SORT_REGULAR);
}
}