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