3 * Zend Framework (http://framework.zend.com/)
5 * @link http://github.com/zendframework/zf2 for the canonical source repository
6 * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
7 * @license http://framework.zend.com/license/new-bsd New BSD License
10 namespace Zend\Stdlib;
15 * ErrorHandler that can be used to catch internal PHP errors
16 * and convert to an ErrorException instance.
18 abstract class ErrorHandler
25 protected static $stack = [];
28 * Check if this error handler is active
32 public static function started()
34 return (bool) static::getNestedLevel();
38 * Get the current nested level
42 public static function getNestedLevel()
44 return count(static::$stack);
48 * Starting the error handler
50 * @param int $errorLevel
52 public static function start($errorLevel = \E_WARNING)
54 if (! static::$stack) {
55 set_error_handler([get_called_class(), 'addError'], $errorLevel);
58 static::$stack[] = null;
62 * Stopping the error handler
64 * @param bool $throw Throw the ErrorException if any
65 * @return null|ErrorException
66 * @throws ErrorException If an error has been caught and $throw is true
68 public static function stop($throw = false)
70 $errorException = null;
73 $errorException = array_pop(static::$stack);
75 if (! static::$stack) {
76 restore_error_handler();
79 if ($errorException && $throw) {
80 throw $errorException;
84 return $errorException;
88 * Stop all active handler
92 public static function clean()
95 restore_error_handler();
102 * Add an error to the stack
105 * @param string $errstr
106 * @param string $errfile
107 * @param int $errline
110 public static function addError($errno, $errstr = '', $errfile = '', $errline = 0)
112 $stack = & static::$stack[count(static::$stack) - 1];
113 $stack = new ErrorException($errstr, 0, $errno, $errfile, $errline, $stack);