aboutsummaryrefslogtreecommitdiff
path: root/src/Main.php
blob: c82a3346ac491a3d6620beefbd2fcb7c6c79b1f0 (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
<?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);
    }

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

        $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);
    }
}