summaryrefslogtreecommitdiff
path: root/src/Middleware/ErrorHandler.php
blob: a7c4cfe62cdc190e77d97d52bfbf9f9cc55e4658 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
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';
    }
}