feat: Implement parsing of PANDOC-style YAML metadata

This commit is contained in:
Dendy 2025-04-14 04:22:07 +02:00
parent a2f716670c
commit 821ea0df16
1 changed files with 34 additions and 1 deletions

View File

@ -9,6 +9,7 @@ use Symfony\Component\Finder\Finder;
use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Process\Process; use Symfony\Component\Process\Process;
use Symfony\Component\Routing\Attribute\Route; use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Yaml\Yaml;
final class MainController extends AbstractController final class MainController extends AbstractController
{ {
@ -46,6 +47,10 @@ final class MainController extends AbstractController
$fs = new Filesystem(); $fs = new Filesystem();
$contents = $fs->exists($fullPath) ? $fs->readFile($fullPath) : null; $contents = $fs->exists($fullPath) ? $fs->readFile($fullPath) : null;
[
'data' => $metadata,
'text' => $text
] = $this->extractMetadata($contents);
// -------------------------------------------------- Get data tree --- // -------------------------------------------------- Get data tree ---
@ -74,9 +79,37 @@ final class MainController extends AbstractController
return $this->render('main/index.html.twig', [ return $this->render('main/index.html.twig', [
'path' => $path, 'path' => $path,
'contents' => $contents, 'contents' => $text,
'metadata' => $metadata,
'tree' => $tree, 'tree' => $tree,
'version' => (new Process(['git', '-C', $gitDir, 'log', '-1', '--oneline']))->mustRun()->getOutput(), 'version' => (new Process(['git', '-C', $gitDir, 'log', '-1', '--oneline']))->mustRun()->getOutput(),
]); ]);
} }
/**
* Parses all YAML metadata blocks in a given string and returns the text
* without such blocks.
*/
private function extractMetadata(?string $text): array
{
if ($text === null) return ['data' => null, 'text' => null];
$start = strpos($text, "---\n");
$end = strpos($text, "...\n", $start) ?: strpos($text, "---\n", $start + 4);
// No more moteadata, return as is. Recursion stop condition
if ($start === false or $end === false) {
return ['text' => $text, 'data' => []];
}
$yaml = Yaml::parse(substr($text, $start + 4, $end - $start - 4));
$rest = substr($text, 0, $start) . substr($text, $end + 4);
// Recurse until there's no more metadata blocks, overwriting as we go
$nextIteration = $this->extractMetadata($rest);
return [
'data' => $nextIteration['data'] + $yaml,
'text' => $nextIteration['text'],
];
}
} }