Completed
Push — master ( b2e200...1332b8 )
by Oscar
04:48
created

ErrorHandler::whoops()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 1
Metric Value
c 3
b 0
f 1
dl 0
loc 6
rs 9.4286
cc 1
eloc 3
nc 1
nop 1
1
<?php
2
3
namespace Psr7Middlewares\Middleware;
4
5
use Psr7Middlewares\Utils;
6
use Psr7Middlewares\Middleware;
7
use Psr\Http\Message\ServerRequestInterface;
8
use Psr\Http\Message\ResponseInterface;
9
10
/**
11
 * Middleware to handle php errors and exceptions.
12
 */
13
class ErrorHandler
14
{
15
    const KEY = 'EXCEPTION';
16
17
    use Utils\HandlerTrait;
18
19
    /**
20
     * @var bool Whether or not catch exceptions
21
     */
22
    private $catchExceptions = false;
23
24
    /**
25
     * Returns the exception throwed.
26
     *
27
     * @param ServerRequestInterface $request
28
     *
29
     * @return \Exception|null
30
     */
31
    public static function getException(ServerRequestInterface $request)
32
    {
33
        return Middleware::getAttribute($request, self::KEY);
34
    }
35
36
    /**
37
     * Configure the catchExceptions.
38
     *
39
     * @param bool $catch
40
     *
41
     * @return self
42
     */
43
    public function catchExceptions($catch = true)
44
    {
45
        $this->catchExceptions = (boolean) $catch;
46
47
        return $this;
48
    }
49
50
    /**
51
     * Execute the middleware.
52
     *
53
     * @param ServerRequestInterface $request
54
     * @param ResponseInterface      $response
55
     * @param callable               $next
56
     *
57
     * @return ResponseInterface
58
     */
59
    public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
60
    {
61
        ob_start();
62
63
        try {
64
            $response = $next($request, $response);
65
        } catch (\Exception $exception) {
66
            if (!$this->catchExceptions) {
67
                throw $exception;
68
            }
69
70
            $request = Middleware::setAttribute($request, self::KEY, $exception);
71
            $response = $response->withStatus(500);
72
        }
73
74
        ob_end_clean();
75
76
        if ($response->getStatusCode() >= 400 && $response->getStatusCode() < 600) {
77
            return $this->executeHandler($request, $response);
78
        }
79
80
        return $response;
81
    }
82
}
83