ErrorHandler.php
1 <?php
2 /**
3  * wCMF - wemove Content Management Framework
4  * Copyright (C) 2005-2015 wemove digital solutions GmbH
5  *
6  * Licensed under the terms of the MIT License.
7  *
8  * See the LICENSE file distributed with this work for
9  * additional information.
10  */
11 namespace wcmf\lib\core;
12 
13 /**
14  * ErrorHandler catches all php errors and transforms fatal
15  * errors into ErrorExceptions and non-fatal into log messages
16  *
17  * @author ingo herwig <ingo@wemove.com>
18  */
19 class ErrorHandler {
20 
21  private static $FATAL_ERRORS = array(E_USER_ERROR => '', E_RECOVERABLE_ERROR => '');
22 
23  private static $_logger = null;
24 
25  /**
26  * Constructor.
27  */
28  public function __construct() {
29  set_error_handler(array($this, 'handleError'));
30  if (self::$_logger == null) {
31  self::$_logger = LogManager::getLogger(__CLASS__);
32  }
33  }
34 
35  /**
36  * Get the stack trace
37  * @return The stack trace as string
38  */
39  public static function getStackTrace() {
40  ob_start();
41  debug_print_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
42  $trace = ob_get_contents();
43  ob_end_clean();
44 
45  // remove first item from backtrace as it's this function which is redundant.
46  $trace = preg_replace('/^#0\s+'.__FUNCTION__."[^\n]*\n/", '', $trace, 1);
47 
48  return $trace;
49  }
50 
51  /**
52  * Actual error handling method
53  * @param $errno
54  * @param $errstr
55  * @param $errfile
56  * @param $errline
57  * @return Boolean
58  * @throws ErrorException
59  */
60  public function handleError($errno, $errstr, $errfile, $errline) {
61  $errorIsEnabled = (bool)($errno & ini_get('error_reporting'));
62 
63  // -- FATAL ERROR
64  if(isset(self::$FATAL_ERRORS[$errno]) && $errorIsEnabled ) {
65  throw new \ErrorException($errstr, 0, $errno, $errfile, $errline);
66  }
67 
68  // -- NON-FATAL ERROR/WARNING/NOTICE
69  else if( $errorIsEnabled ) {
70  self::$_logger->warn($errstr);
71  return false; // Make sure this ends up in $php_errormsg, if appropriate
72  }
73  }
74 }
75 ?>
static getLogger($name)
Get the logger with the given name.
Definition: LogManager.php:35
__construct()
Constructor.
handleError($errno, $errstr, $errfile, $errline)
Actual error handling method.
ErrorHandler catches all php errors and transforms fatal errors into ErrorExceptions and non-fatal in...
static getStackTrace()
Get the stack trace.
Core classes.
Definition: namespaces.php:11