diff options
author | Laria Carolin Chabowski <laria@laria.me> | 2020-02-07 09:44:59 +0100 |
---|---|---|
committer | Laria Carolin Chabowski <laria@laria.me> | 2020-02-07 09:44:59 +0100 |
commit | 2eb5a432d2229788ce2fdb09f36c6f4bebdea813 (patch) | |
tree | ab57978bdda34c82b025b897cfb6825b1fd1e654 /src/Main.php | |
download | micropoly-2eb5a432d2229788ce2fdb09f36c6f4bebdea813.tar.gz micropoly-2eb5a432d2229788ce2fdb09f36c6f4bebdea813.tar.bz2 micropoly-2eb5a432d2229788ce2fdb09f36c6f4bebdea813.zip |
Initial commit
Diffstat (limited to 'src/Main.php')
-rw-r--r-- | src/Main.php | 58 |
1 files changed, 58 insertions, 0 deletions
diff --git a/src/Main.php b/src/Main.php new file mode 100644 index 0000000..443960b --- /dev/null +++ b/src/Main.php @@ -0,0 +1,58 @@ +<?php + +namespace Micropoly; + +use Closure; +use FastRoute\Dispatcher; +use FastRoute\RouteCollector; +use Micropoly\Handlers\ApiTagsHandler; +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 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); + } + + 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); + } +} |