1 | <?php |
||
12 | class ErrorHandler implements ErrorHandlerInterface, LoggerAwareInterface |
||
13 | { |
||
14 | use ErrorHandler\Logging; |
||
15 | use ErrorHandler\ErrorCodes; |
||
16 | use ErrorHandler\HandleUncaughtError; |
||
17 | use ErrorHandler\HandleShutdownError; |
||
18 | use ErrorHandler\HandleUncaughtException; |
||
19 | use ErrorHandler\FunctionWrapper; |
||
20 | |||
21 | |||
22 | /** |
||
23 | * @var \Exception|\Error |
||
24 | */ |
||
25 | protected $error; |
||
26 | |||
27 | /** |
||
28 | * @var callback |
||
29 | */ |
||
30 | protected $onFatalError; |
||
31 | |||
32 | |||
33 | /** |
||
34 | * Set the caught error |
||
35 | * |
||
36 | * @param \Throwable|\Exception|\Error |
||
37 | */ |
||
38 | 4 | public function setError($error) |
|
48 | |||
49 | /** |
||
50 | * Get the caught error |
||
51 | * |
||
52 | * @return \Throwable|\Exception|\Error |
||
53 | */ |
||
54 | 4 | public function getError() |
|
58 | |||
59 | |||
60 | /** |
||
61 | * Use this error handler as middleware |
||
62 | */ |
||
63 | 2 | public function asMiddleware() |
|
67 | |||
68 | |||
69 | /** |
||
70 | * Log these types of errors or exceptions |
||
71 | * |
||
72 | * @param int|string $type E_* contants as binary set OR Exception class name |
||
73 | */ |
||
74 | 86 | public function logUncaught($type) |
|
75 | { |
||
76 | 86 | if (is_int($type)) { |
|
77 | 68 | $this->logUncaughtErrors($type); |
|
78 | 20 | } elseif (is_string($type)) { |
|
79 | 18 | $this->logUncaughtException($type); |
|
80 | } else { |
||
81 | 2 | throw new \InvalidArgumentException("Type should be an error code (int) or Exception class (string)"); |
|
82 | } |
||
83 | 84 | } |
|
84 | |||
85 | |||
86 | /** |
||
87 | * Set a callback for when the script dies because of a fatal, non-catchable error. |
||
88 | * The callback should have an `ErrorException` as only argument. |
||
89 | * |
||
90 | * @param callable $callback |
||
91 | * @param boolean $clearOutput Clear the output buffer before calling the callback |
||
92 | */ |
||
93 | 8 | public function onFatalError($callback, $clearOutput = false) |
|
94 | { |
||
95 | 8 | if (!$clearOutput) { |
|
96 | 4 | $this->onFatalError = $callback; |
|
97 | } else { |
||
98 | 4 | $this->onFatalError = function ($error) use ($callback) { |
|
99 | 4 | $this->clearOutputBuffer(); |
|
100 | 4 | $callback($error); |
|
101 | 4 | }; |
|
102 | } |
||
103 | 8 | } |
|
104 | |||
105 | /** |
||
106 | * Run the fatal error callback |
||
107 | * |
||
108 | * @param \Exception|\Error $error |
||
109 | */ |
||
110 | 28 | protected function callOnFatalError($error) |
|
111 | { |
||
112 | 28 | if ($this->onFatalError) { |
|
113 | 8 | call_user_func($this->onFatalError, $error); |
|
114 | } |
||
115 | 28 | } |
|
116 | |||
117 | /** |
||
118 | * Clear and destroy all the output buffers |
||
119 | * @codeCoverageIgnore |
||
120 | */ |
||
121 | protected function clearOutputBuffer() |
||
127 | } |
||
128 | |||
129 |