summaryrefslogtreecommitdiff
path: root/src/Middleware/ErrorHandler.php
diff options
context:
space:
mode:
authorIgor Scheller <igor.scheller@igorshp.de>2018-09-08 12:48:08 +0200
committerIgor Scheller <igor.scheller@igorshp.de>2018-09-09 12:11:12 +0200
commit222c9fed7d4ca2b3b44c05907fbb7080c1efd342 (patch)
tree62b1bfa9233000985331b9dea703d51dc24515a2 /src/Middleware/ErrorHandler.php
parent2d6bca1357faff28bc1f86a56b432cc463ff7574 (diff)
parent8257864829ffdfb410f05e0dd0a9c781f48b741a (diff)
Merge remote-tracking branch 'MyIgel/templating'
Diffstat (limited to 'src/Middleware/ErrorHandler.php')
-rw-r--r--src/Middleware/ErrorHandler.php80
1 files changed, 80 insertions, 0 deletions
diff --git a/src/Middleware/ErrorHandler.php b/src/Middleware/ErrorHandler.php
new file mode 100644
index 00000000..a7c4cfe6
--- /dev/null
+++ b/src/Middleware/ErrorHandler.php
@@ -0,0 +1,80 @@
+<?php
+
+namespace Engelsystem\Middleware;
+
+use Engelsystem\Http\Response;
+use Psr\Http\Message\ResponseInterface;
+use Psr\Http\Message\ServerRequestInterface;
+use Psr\Http\Server\MiddlewareInterface;
+use Psr\Http\Server\RequestHandlerInterface;
+use Twig_LoaderInterface as TwigLoader;
+
+class ErrorHandler implements MiddlewareInterface
+{
+ /** @var TwigLoader */
+ protected $loader;
+
+ /** @var string */
+ protected $viewPrefix = 'errors/';
+
+ /**
+ * @param TwigLoader $loader
+ */
+ public function __construct(TwigLoader $loader)
+ {
+ $this->loader = $loader;
+ }
+
+ /**
+ * Handles any error messages
+ *
+ * Should be added at the beginning
+ *
+ * @param ServerRequestInterface $request
+ * @param RequestHandlerInterface $handler
+ * @return ResponseInterface
+ */
+ public function process(
+ ServerRequestInterface $request,
+ RequestHandlerInterface $handler
+ ): ResponseInterface {
+ $response = $handler->handle($request);
+
+ $statusCode = $response->getStatusCode();
+ if ($statusCode < 400 || !$response instanceof Response) {
+ return $response;
+ }
+
+ $view = $this->selectView($statusCode);
+
+ return $response->withView(
+ $this->viewPrefix . $view,
+ [
+ 'status' => $statusCode,
+ 'content' => $response->getContent(),
+ ],
+ $statusCode,
+ $response->getHeaders()
+ );
+ }
+
+ /**
+ * Select a view based on the given status code
+ *
+ * @param int $statusCode
+ * @return string
+ */
+ protected function selectView(int $statusCode): string
+ {
+ $hundreds = intdiv($statusCode, 100);
+
+ $viewsList = [$statusCode, $hundreds, $hundreds * 100];
+ foreach ($viewsList as $view) {
+ if ($this->loader->exists($this->viewPrefix . $view)) {
+ return $view;
+ }
+ }
+
+ return 'default';
+ }
+}