aboutsummaryrefslogtreecommitdiff
path: root/src/Main.php
blob: 21c7a95c32c967b608929477b173e23ef1f8825b (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
<?php

namespace Micropoly;

use Closure;
use FastRoute\Dispatcher;
use FastRoute\RouteCollector;
use Micropoly\Handlers\ApiTagsHandler;
use Micropoly\Handlers\AttachmentHandler;
use Micropoly\Handlers\Index;
use Micropoly\Handlers\MethodNotAllowedHandler;
use Micropoly\Handlers\NewNote;
use Micropoly\Handlers\NoteHandler;
use Micropoly\Handlers\NotFoundHandler;

use Micropoly\Handlers\Search;
use Micropoly\Models\Attachment;
use function FastRoute\simpleDispatcher;

class Main implements Entrypoint
{
    private static function buildRoutes(RouteCollector $r)
    {
        $r->addRoute(["GET"], "/", Index::class);
        $r->addRoute(["GET", "POST"], "/new-note", NewNote::class);
        $r->addRoute(["GET"], "/search", Search::class);
        $r->addRoute(["GET", "POST"], "/n/{id}", NoteHandler::class);
        $r->addRoute(["GET"], "/api/tags", ApiTagsHandler::class);
        $r->addRoute(["GET"], "/attachments/{id}", AttachmentHandler::class);
    }

    private static function populateGET(): void
    {
        $parts = explode("?", $_SERVER["REQUEST_URI"]);
        if (isset($parts[1]))
            parse_str($parts[1], $_GET);
    }

    public function run(Env $env)
    {
        $disp = simpleDispatcher(Closure::fromCallable([self::class, "buildRoutes"]));

        self::populateGET();

        $uri = preg_replace('/\?.*$/', "", $_SERVER["REQUEST_URI"]);
        $result = $disp->dispatch($_SERVER["REQUEST_METHOD"], $uri);
        switch ($result[0]) {
            case Dispatcher::NOT_FOUND:
                $handlerCls = NotFoundHandler::class;
                $vars = [];
                break;
            case Dispatcher::FOUND:
                [, $handlerCls, $vars] = $result;
                break;
            case Dispatcher::METHOD_NOT_ALLOWED:
                $handlerCls = MethodNotAllowedHandler::class;
                $vars = ["allowed" => $result[1]];
                break;
            default:
                throw new \DomainException("Unexpected routing result: {$result[0]}");
        }

        $handler = new $handlerCls();
        if (!($handler instanceof Handler)) {
            throw new \DomainException("handler is not an instance of ".Handler::class);
        }

        $handler->handle($env, $vars);
    }
}