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
|
|
|
|