Completed
Push — master ( 00ed35...63fbb3 )
by Oscar
10:20
created

ErrorHandler::defaultHandler()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 22
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 22
rs 9.2
cc 2
eloc 10
nc 2
nop 2
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\CallableTrait;
18
19
    /**
20
     * @var callable|string The handler used
21
     */
22
    private $handler;
23
24
    /**
25
     * @var bool Whether or not catch exceptions
26
     */
27
    private $catchExceptions = false;
28
29
    /**
30
     * Returns the exception throwed.
31
     *
32
     * @param ServerRequestInterface $request
33
     *
34
     * @return \Exception|null
35
     */
36
    public static function getException(ServerRequestInterface $request)
37
    {
38
        return Middleware::getAttribute($request, self::KEY);
39
    }
40
41
    /**
42
     * Constructor.
43
     *
44
     * @param callable|string|null $handler
45
     */
46
    public function __construct($handler = null)
47
    {
48
        $this->handler = $handler ?: self::CLASS.'::defaultHandler';
49
    }
50
51
    /**
52
     * Configure the catchExceptions.
53
     *
54
     * @param bool $catch
55
     *
56
     * @return self
57
     */
58
    public function catchExceptions($catch = true)
59
    {
60
        $this->catchExceptions = (boolean) $catch;
61
62
        return $this;
63
    }
64
65
    /**
66
     * Execute the middleware.
67
     *
68
     * @param ServerRequestInterface $request
69
     * @param ResponseInterface      $response
70
     * @param callable               $next
71
     *
72
     * @return ResponseInterface
73
     */
74
    public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
75
    {
76
        try {
77
            ob_start();
78
            $level = ob_get_level();
79
            $response = $next($request, $response);
80
        } catch (\Exception $exception) {
81
            if (!$this->catchExceptions) {
82
                throw $exception;
83
            }
84
85
            $request = Middleware::setAttribute($request, self::KEY, $exception);
86
            $response = $response->withStatus(500);
87
        } finally {
88
            Utils\Helpers::getOutput($level);
0 ignored issues
show
Bug introduced by
The variable $level does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
89
        }
90
91
        if ($response->getStatusCode() >= 400 && $response->getStatusCode() < 600) {
92
            return $this->executeCallable($this->handler, $request, $response);
93
        }
94
95
        return $response;
96
    }
97
98
    public static function defaultHandler(ServerRequestInterface $request, ResponseInterface $response)
99
    {
100
        $exception = self::getException($request);
101
102
        $message = $exception ? $exception->getMessage() : $response->getReasonPhrase();
103
        $statusCode = $response->getStatusCode();
104
105
        return <<<EOT
106
<!DOCTYPE html>
107
<html>
108
<head>
109
    <meta charset="utf-8">
110
    <title>Error {$statusCode}</title>
111
    <meta name="viewport" content="width=device-width, initial-scale=1">
112
</head>
113
<body>
114
    <h1>Error {$statusCode}</h1>
115
    <p>{$message}</p>
116
</body>
117
</html>
118
EOT;
119
    }
120
}
121