70 lines
1.7 KiB
PHP
70 lines
1.7 KiB
PHP
<?php namespace CodeSpace\Wiki;
|
|
|
|
class DataSource {
|
|
|
|
private string $docs_path;
|
|
|
|
public function __construct() {
|
|
$this->docs_path = realpath("../docs/");
|
|
}
|
|
|
|
private function extractFrontMatter($content) {
|
|
$frontMatter = [];
|
|
$parts = preg_split('/^---\R/m', $content, 2, PREG_SPLIT_NO_EMPTY);
|
|
if (count($parts) > 1) {
|
|
$frontMatterSection = trim($parts[0]);
|
|
$lines = explode("\n", $frontMatterSection);
|
|
foreach ($lines as $line) {
|
|
$parts = explode(':', $line, 2);
|
|
if (count($parts) === 2) {
|
|
$key = trim($parts[0]);
|
|
$value = trim($parts[1]);
|
|
$frontMatter[$key] = $value;
|
|
}
|
|
}
|
|
}
|
|
return $frontMatter;
|
|
}
|
|
|
|
private function stripFrontMatter($content) {
|
|
$parts = preg_split('/^---\R/m', $content, 2, PREG_SPLIT_NO_EMPTY);
|
|
if (count($parts) > 1) {
|
|
return trim($parts[1]);
|
|
}
|
|
return $content;
|
|
}
|
|
|
|
public function getMarkdown(string $file): array {
|
|
$content = file_get_contents($file);
|
|
if (!$content) return [null, []];
|
|
$frontmatter = $this->extractFrontMatter($content);
|
|
$markdown = $this->stripFrontMatter($content);
|
|
return [$markdown, $frontmatter];
|
|
}
|
|
|
|
public function getMenu(string $file): ?array {
|
|
$path = dirname($file);
|
|
while (strlen($this->docs_path) <= strlen($path)) {
|
|
$menu_file = "$path/menu.json";
|
|
if (file_exists($menu_file)) {
|
|
$data = file_get_contents($menu_file);
|
|
return $data ? json_decode($data, true) : null;
|
|
}
|
|
$path = dirname($path);
|
|
}
|
|
return null;
|
|
}
|
|
|
|
public function getFile(string $slug): string {
|
|
if (!$slug) $slug = "index";
|
|
$files = [
|
|
"$this->docs_path/$slug.md",
|
|
"$this->docs_path/$slug/index.md"
|
|
];
|
|
foreach ($files as &$file) {
|
|
if (file_exists($file)) return $file;
|
|
}
|
|
return $files[1];
|
|
}
|
|
|
|
} |