webhook management
[pharext/pharext.org] / app / Web.php
1 <?php
2
3 namespace app;
4
5 use http\Env\Request;
6 use http\Env\Response;
7
8 use FastRoute\Dispatcher;
9 use League\Plates;
10
11 class Web
12 {
13 private $baseUrl;
14 private $request;
15 private $response;
16 private $view;
17
18 function __construct(BaseUrl $baseUrl, Request $request, Response $response, Plates\Engine $view) {
19 $this->baseUrl = $baseUrl;
20 $this->request = $request;
21 $this->response = $response;
22 $this->view = $view->addData(["location" => null]);
23 ob_start($response);
24 }
25
26 function __invoke(Dispatcher $dispatcher) {
27 $route = $dispatcher->dispatch($this->request->getRequestMethod(),
28 $this->baseUrl->pathinfo($this->request->getRequestUrl()));
29
30 switch ($route[0]) {
31 case Dispatcher::NOT_FOUND:
32 $this->response->setResponseCode(404);
33 $this->response->getBody()->append($this->view->render("404"));
34 break;
35
36 case Dispatcher::METHOD_NOT_ALLOWED:
37 $this->response->setResponseCode(405);
38 $this->response->setHeader("Allowed", $route[1]);
39 $this->response->getBody()->append($this->view->render("405"));
40 break;
41
42 case Dispatcher::FOUND:
43 list(, $handler, $args) = $route;
44 $handler(array_map("urldecode", $args));
45 break;
46 }
47
48 $this->response->send();
49 }
50
51 function display($view, array $data = []) {
52 $this->response->getBody()->append(
53 $this->view->render($view, $data));
54 }
55
56 function redirect($url, $code = 302) {
57 $this->response->setResponseCode($code);
58 $this->response->setHeader("Location", $url);
59 }
60
61 function getBaseUrl() {
62 return $this->baseUrl;
63 }
64
65 function getView() {
66 return $this->view;
67 }
68
69 function getRequest() {
70 return $this->request;
71 }
72
73 function getResponse() {
74 return $this->response;
75 }
76 }