about summary refs log tree commit diff stats
path: root/classes/Router.php
blob: 13e967e62d9cca9ec01251647bdcd261497d7e5e (plain) (blame)
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
<?php

class Router
{
    /** @var array<string, RequestHandlerInterface> */
    private array $routes = [];

    /** @var MiddlewareInterface[] */
    private array $middleware = [];

    public function addRoute(string $op, RequestHandlerInterface $handler): void
    {
        $this->routes[$op] = $handler;
    }

    public function addMiddleware(MiddlewareInterface $middleware): void
    {
        $this->middleware[] = $middleware;
    }

    /**
     * Dispatch an operation and send the response.
     * Calls exit after sending the response.
     */
    public function dispatch(string $op): void
    {
        $response = $this->dispatchResponse($op);
        $response->send();
        exit;
    }

    /**
     * Get the Response for a dispatch without sending it.
     * Used for testing and for cases where the caller
     * wants to modify the response before sending.
     */
    public function dispatchResponse(string $op): Response
    {
        $handler = $this->routes[$op] ?? null;

        if (!$handler) {
            return (new Response())
                ->withStatus(404)
                ->withBody(json_encode(["error" => "Method not found"]));
        }

        // Check auth for handlers that require it
        if ($handler instanceof AuthRequired && !validate_session()) {
            return (new Response())
                ->withStatus(401)
                ->withBody(json_encode(["error" => "Unauthorized"]));
        }

        $pipe = $handler->handle(...);

        // wrap middleware in reverse order (last added = outermost)
        foreach (array_reverse($this->middleware) as $mw) {
            $previous = $pipe;
            $pipe = fn(Request $r) => $mw->process($r, $previous);
        }

        $request = new Request();
        $request = $request->withAttribute('op', $op);

        return $pipe($request);
    }
}