1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Protoku\Exceptions; |
4
|
|
|
|
5
|
|
|
use ErrorException; |
6
|
|
|
use Protoku\Interfaces\FormatterInterface; |
7
|
|
|
|
8
|
|
|
class Handler |
9
|
|
|
{ |
10
|
|
|
const ERROR_HANDLER = 'handleError'; |
11
|
|
|
const EXCEPTION_HANDLER = 'handleException'; |
12
|
|
|
const SHUTDOWN_HANDLER = 'handleShutdown'; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* @var FormatterInterface |
16
|
|
|
*/ |
17
|
|
|
private $formatter; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* Handler constructor. |
21
|
|
|
* |
22
|
|
|
* @param FormatterInterface $formatter |
23
|
|
|
*/ |
24
|
|
|
public function __construct(FormatterInterface $formatter) |
25
|
|
|
{ |
26
|
|
|
$this->formatter = $formatter; |
27
|
|
|
$this->registerErrorHandler(); |
28
|
|
|
$this->registerExceptionHandler(); |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* Register the PHP error handler. |
33
|
|
|
* |
34
|
|
|
* @return void |
35
|
|
|
*/ |
36
|
|
|
protected function registerErrorHandler() |
37
|
|
|
{ |
38
|
|
|
set_error_handler([$this, self::ERROR_HANDLER]); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* Register the PHP exception handler. |
43
|
|
|
* |
44
|
|
|
* @return void |
45
|
|
|
*/ |
46
|
|
|
protected function registerExceptionHandler() |
47
|
|
|
{ |
48
|
|
|
set_exception_handler([$this, self::EXCEPTION_HANDLER]); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* Register a function for execution on shutdown |
53
|
|
|
* |
54
|
|
|
* @return void |
55
|
|
|
*/ |
56
|
|
|
protected function registerShutdownHandler() |
57
|
|
|
{ |
58
|
|
|
register_shutdown_function(self::SHUTDOWN_HANDLER); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* @param int $level |
63
|
|
|
* @param string $message |
64
|
|
|
* @param string $file |
65
|
|
|
* @param int $line |
66
|
|
|
* @param array $context |
67
|
|
|
* |
68
|
|
|
* @throws ErrorException |
69
|
|
|
*/ |
70
|
|
|
public function handleError(int $level, string $message, string $file = '', int $line = 0, array $context = []) |
|
|
|
|
71
|
|
|
{ |
72
|
|
|
throw new ErrorException($message, 0, $level, $file, $line); |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
/** |
76
|
|
|
* @param \Throwable $e |
77
|
|
|
*/ |
78
|
|
|
public function handleException(\Throwable $e) |
79
|
|
|
{ |
80
|
|
|
ob_start(); |
81
|
|
|
$response = json_encode($this->formatter->format($e)); |
82
|
|
|
ob_end_clean(); |
83
|
|
|
http_response_code(500); |
84
|
|
|
print $response; |
85
|
|
|
return; |
86
|
|
|
} |
87
|
|
|
|
88
|
|
|
/** |
89
|
|
|
* |
90
|
|
|
*/ |
91
|
|
|
public function handleShutdown() |
92
|
|
|
{ |
93
|
|
|
$error = error_get_last(); |
94
|
|
|
|
95
|
|
|
if ($error) { |
|
|
|
|
96
|
|
|
$this->handleException(new ErrorException($error['type'], $error['message'], $error['file'], $error['line'])); |
97
|
|
|
} |
98
|
|
|
} |
99
|
|
|
} |
This check looks from parameters that have been defined for a function or method, but which are not used in the method body.