aboutsummaryrefslogtreecommitdiff
path: root/src/Env.php
blob: 9e6ba51ffdb8e329f7c81ffc78e3e54c05064aaa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
<?php

namespace Micropoly;

use RuntimeException;
use SQLite3;
use Twig\Environment;
use Twig\Loader\FilesystemLoader;
use Twig\TwigFilter;
use Twig\TwigFunction;

class Env
{
    private array $config;

    private function __construct() { }

    private array $lazyLoaded = [];

    private function lazy(string $ident, callable $callback)
    {
        if (!isset($this->lazyLoaded[$ident])) {
            $this->lazyLoaded[$ident] = $callback();
        }
        return $this->lazyLoaded[$ident];
    }

    public static function fromConfig(array $config)
    {
        $env = new self;
        $env->config = $config;
        return $env;
    }

    public function documentRoot(): string { return "/"; }

    public function twig(): Environment
    {
        return $this->lazy("twig", function () {
            $loader = new FilesystemLoader($this->config["templates_path"]);
            $env = new Environment($loader, [
                "cache" => $this->config["templates_cache"] ?? false,
            ]);

            $env->addFunction(new TwigFunction("url", function (string $url, ...$args) {
                return $this->documentRoot() . sprintf($url, ...$args);
            }, ["is_variadic" => true]));

            $env->addFilter(new TwigFilter("search_escape", static function (string $s) {
                $s = str_replace("\\", "\\\\", $s);
                $s = str_replace("#", "\\#", $s);
                $s = str_replace(" ", "\\ ", $s);
                $s = str_replace("\t", "\\\t", $s);
                $s = str_replace("(", "\\(", $s);
                $s = str_replace(")", "\\)", $s);
                return $s;
            }));

            return $env;
        });
    }

    public function rawDbCon(): SQLite3
    {
        return $this->lazy("rawDbCon", function () {
            return new SQLite3($this->config["sqlitedb"]);
        });
    }

    public function db(): SQLite3
    {
        return $this->lazy("db", function () {
            $db = $this->rawDbCon();
            $db->exec("PRAGMA foreign_keys = ON");

            (new Schema($db))->migrate();

            return $db;
        });
    }

    public function attachmentsPath(): string
    {
        $attachments = $this->config['attachments'];
        if (!is_dir($attachments) || !is_writable($attachments))
            throw new RuntimeException("Attachment directory '$attachments' is not a writable directory.");
        return $attachments;
    }
}