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