implement simple maintenance switch
[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 if (!file_exists("../config/maintenance")) {
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->display(404, null, 404);
34 break;
35
36 case Dispatcher::METHOD_NOT_ALLOWED:
37 $this->display(405, null, 405, ["Allowed" => $route[1]]);
38 break;
39
40 case Dispatcher::FOUND:
41 list(, $handler, $args) = $route;
42 try {
43 $handler(array_map("urldecode", $args));
44 } catch (\Exception $exception) {
45 self::cleanBuffers();
46 $this->display(500, compact("exception"), 500, ["X-Exception", get_class($exception)]);
47 }
48 break;
49 }
50 } else {
51 $this->display(503, null, 503);
52 }
53
54 $this->response->send();
55 }
56
57 function display($view, array $data = null, $code = null, array $headers = []) {
58 if (isset($code)) {
59 $this->response->setResponseCode($code);
60 }
61 if ($headers) {
62 $this->response->addHeaders($headers);
63 }
64 $this->response->getBody()->append(
65 $this->view->render($view, (array) $data));
66 }
67
68 function redirect($url, $code = 302) {
69 $this->response->setResponseCode($code);
70 $this->response->setHeader("Location", $url);
71 }
72
73 function getBaseUrl() {
74 return $this->baseUrl;
75 }
76
77 function getView() {
78 return $this->view;
79 }
80
81 function getRequest() {
82 return $this->request;
83 }
84
85 function getResponse() {
86 return $this->response;
87 }
88
89 static function cleanBuffers() {
90 while (ob_get_level()) {
91 if (!@ob_end_clean()) {
92 break;
93 }
94 }
95 }
96 }