LightWiki/src/Engine.php
2024-03-09 12:09:34 +01:00

57 lines
1.4 KiB
PHP

<?php namespace CodeSpace\Wiki;
use ParsedownExtra;
class Engine {
public ParsedownExtra $parsedown;
public \Twig\Environment $twig;
public array $config;
public string $slug;
public function __construct(array $config) {
$this->config = $config;
$this->slug = $this->getSlug();
$loader = new \Twig\Loader\FilesystemLoader(dirname(__DIR__) . "/view/");
$this->twig = new \Twig\Environment($loader, [
// "cache" => "../cache",
]);
$this->twig->addFilter(new \Twig\TwigFilter('isActive', function ($link) {
return "/$this->slug" == $link;
}));
$this->parsedown = new ParsedownExtra();
}
public function getSlug(): string {
$slug = parse_url(array_key_exists("slug", $_REQUEST) ? "/" . $_REQUEST["slug"] : $_SERVER["REQUEST_URI"], PHP_URL_PATH);
return trim($slug, "/");
}
public function template(string $view, array $data = []) {
return $this->twig->render("$view.twig", [
"config" => $this->config,
...$data
]);
}
function render() {
$data = new DataSource();
$file = $data->getFile($this->slug);
$menu = $data->getMenu($file);
[$markdown, $meta] = $data->getMarkdown($file);
if (!$markdown) return $this->template("404", ["menu" => $menu]);
return $this->template("page", [
"content" => $this->parsedown->text($markdown),
"meta" => array_merge($this->config["meta"], $meta),
"menu" => $menu
]);
}
public function display() {
echo $this->render();
}
}