src/Controller/SidebarController.php line 15

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use Parsedown;
  4. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  5. use Symfony\Component\Filesystem\Filesystem;
  6. use Symfony\Component\HttpFoundation\Response;
  7. use Symfony\Component\Routing\Annotation\Route;
  8. use voku\helper\HtmlDomParser;
  9. class SidebarController extends AbstractController
  10. {
  11.     #[Route('/sidebar'name'app_sidebar')]
  12.     public function index(): Response
  13.     {
  14.         $filePathSidebar $this->getParameter('kernel.project_dir') . "/mxo-docs/_sidebar.md";
  15.         $filesystem = new Filesystem();
  16.         $links = array();
  17.         if ($filesystem->exists($filePathSidebar)) {
  18.             $links $this->parseSidebar($filePathSidebar);
  19.         }
  20.         return $this->render('sidebar/_menu_entries.html.twig', [
  21.             'menuEntries' => $links
  22.         ]);
  23.     }
  24.     function parseSidebar($file)
  25.     {
  26.         // Datei in String laden
  27.         $content file_get_contents($file);
  28.         // Markdown-Parser initialisieren
  29.         $parser = new Parsedown();
  30.         // Markdown in HTML parsen
  31.         $html $parser->text($content);
  32.         $html "<div>" $html "</div>";
  33.         $html str_replace('<div><ul>','<div><ul class="first">'$html);
  34.         $dom HtmlDomParser::str_get_html($html);
  35.         // HTML-Elemente in Array konvertieren
  36.         $elements $dom->find('ul.first > li');
  37.         // Sidebar-Array initialisieren
  38.         $sidebar = array();
  39.         foreach ($elements as $item) {
  40.             $link $item->find('a')[0]->getAttribute('href');
  41.             $text $item->find('a')[0]->textContent;
  42.             // Sublinks parsen
  43.             $sublinks = array();
  44.             $subitems $item->find('ul li a');#
  45.             if ($subitems->count() > 0) {
  46.                 foreach ($subitems as $subitem) {
  47.                     $sublinks[] = array(
  48.                         'link' => ltrim($subitem->find('a')[0]->getAttribute('href'), '.'),
  49.                         'text' => trim($subitem->find('a')[0]->textContent),
  50.                     );
  51.                 }
  52.             }
  53.             if(count($sublinks)>0){
  54.                 $sublinks array_unique($sublinksSORT_REGULAR);
  55.             }
  56.             $sidebar[] = array(
  57.                 'link' => ltrim($link'.'),
  58.                 'text' => trim($text),
  59.                 'sublinks' => $sublinks,
  60.             );
  61.         }
  62.         // Sidebar-Array zurückgeben
  63.         return array_unique($sidebarSORT_REGULAR);
  64.     }
  65. }