| 1 |
<?php |
| 2 |
|
| 3 |
namespace FluentForm\Framework\Exception; |
| 4 |
|
| 5 |
class ExceptionHandler |
| 6 |
{ |
| 7 |
const APPEND_TO_LOG_FILE = 3; |
| 8 |
|
| 9 |
/** |
| 10 |
* framework\App\Application |
| 11 |
* @var Object |
| 12 |
*/ |
| 13 |
protected $app = null; |
| 14 |
|
| 15 |
public function __construct($app) |
| 16 |
{ |
| 17 |
$this->app = $app; |
| 18 |
$this->registerHandlers(); |
| 19 |
} |
| 20 |
|
| 21 |
public function registerHandlers() |
| 22 |
{ |
| 23 |
error_reporting(-1); |
| 24 |
set_error_handler([$this, 'handleError']); |
| 25 |
set_exception_handler([$this, 'handleException']); |
| 26 |
register_shutdown_function([$this, 'handleShutdown']); |
| 27 |
} |
| 28 |
|
| 29 |
public function handleError($severity, $message, $file = '', $line = 0) |
| 30 |
{ |
| 31 |
if (error_reporting() & $severity) { |
| 32 |
throw new \ErrorException($message, 0, $severity, $file, $line); |
| 33 |
} |
| 34 |
} |
| 35 |
|
| 36 |
public function handleException($e) |
| 37 |
{ |
| 38 |
try { |
| 39 |
$this->report($e); |
| 40 |
$this->render($e); |
| 41 |
} catch (\Exception $e) { |
| 42 |
die($e->getMessage().' : '.$e->getFile().' ('.$e->getLine().')'); |
| 43 |
} |
| 44 |
} |
| 45 |
|
| 46 |
public function handleShutdown() |
| 47 |
{ |
| 48 |
if (!is_null($error = error_get_last()) && $this->isFatal($error['type'])) { |
| 49 |
$this->handleException(new \ErrorException( |
| 50 |
$error['message'], 0, $error['type'], $error['file'], $error['line'] |
| 51 |
)); |
| 52 |
} |
| 53 |
} |
| 54 |
|
| 55 |
public function report($e) |
| 56 |
{ |
| 57 |
$logDir = $this->app->storagePath('logs'); |
| 58 |
if (!is_readable($logDir)) { |
| 59 |
mkdir($logDir, 0777); |
| 60 |
} |
| 61 |
|
| 62 |
error_log( |
| 63 |
'['.date('Y-m-d H:i:s').'] '.(string) $e, |
| 64 |
self::APPEND_TO_LOG_FILE, |
| 65 |
$logDir.'/error.log' |
| 66 |
); |
| 67 |
} |
| 68 |
|
| 69 |
public function render($e) |
| 70 |
{ |
| 71 |
echo get_class($e) .' : '. $e->getMessage() . ' in ' . $e->getFile() . ' (' . $e->getLine() . ')'; |
| 72 |
echo '<br><pre>' . str_replace("\n", '<br>', $e->getTraceAsString()) . '</pre>'; |
| 73 |
} |
| 74 |
|
| 75 |
protected function isFatal($type) |
| 76 |
{ |
| 77 |
return in_array($type, [E_COMPILE_ERROR, E_CORE_ERROR, E_ERROR, E_PARSE]); |
| 78 |
} |
| 79 |
} |
| 80 |
|