| 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 |
try { |
| 32 |
if (error_reporting() & $severity) { |
| 33 |
throw new \ErrorException($message, 0, $severity, $file, $line); |
| 34 |
} |
| 35 |
} catch(\Exception $e) { |
| 36 |
$this->handleException($e); |
| 37 |
} |
| 38 |
} |
| 39 |
|
| 40 |
public function handleException($e) |
| 41 |
{ |
| 42 |
try { |
| 43 |
if ($this->app->getEnv() != 'production') { |
| 44 |
$this->report($e); |
| 45 |
$this->render($e); |
| 46 |
} |
| 47 |
} catch (\Exception $e) { |
| 48 |
wp_die( |
| 49 |
'<pre>' |
| 50 |
. $e->getMessage().' : '.$e->getFile().' ('.$e->getLine().')' . |
| 51 |
'</pre>' |
| 52 |
); |
| 53 |
} |
| 54 |
} |
| 55 |
|
| 56 |
public function handleShutdown() |
| 57 |
{ |
| 58 |
if (!is_null($error = error_get_last()) && $this->isFatal($error['type'])) { |
| 59 |
$this->handleException(new \ErrorException( |
| 60 |
$error['message'], 0, $error['type'], $error['file'], $error['line'] |
| 61 |
)); |
| 62 |
} |
| 63 |
} |
| 64 |
|
| 65 |
public function report($e) |
| 66 |
{ |
| 67 |
$logDir = $this->app->storagePath('logs'); |
| 68 |
|
| 69 |
if (!is_readable($logDir)) { |
| 70 |
mkdir($logDir, 0777); |
| 71 |
} |
| 72 |
|
| 73 |
//Log in: wp-content/debug.log |
| 74 |
if (defined('WP_DEBUG_LOG') && WP_DEBUG_LOG) { |
| 75 |
error_log((string) $e); |
| 76 |
} |
| 77 |
|
| 78 |
//Log in: plugin-root-dir/storage/logs/error.log |
| 79 |
error_log( |
| 80 |
'['.current_time('mysql').'] ' . (string) $e, |
| 81 |
self::APPEND_TO_LOG_FILE, |
| 82 |
$logDir.'/error.log' |
| 83 |
); |
| 84 |
} |
| 85 |
|
| 86 |
public function render($e) |
| 87 |
{ |
| 88 |
echo get_class($e) .' : '. $e->getMessage() . ' in ' . $e->getFile() . ' (' . $e->getLine() . ')'; |
| 89 |
echo '<br><pre>' . str_replace("\n", '<br>', $e->getTraceAsString()) . '</pre>'; |
| 90 |
} |
| 91 |
|
| 92 |
protected function isFatal($type) |
| 93 |
{ |
| 94 |
return in_array($type, [E_COMPILE_ERROR, E_CORE_ERROR, E_ERROR, E_PARSE]); |
| 95 |
} |
| 96 |
} |
| 97 |
|