ErrorHandler.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. <?php
  2. /**
  3. * Zend Framework (http://framework.zend.com/)
  4. *
  5. * @link http://github.com/zendframework/zf2 for the canonical source repository
  6. * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
  7. * @license http://framework.zend.com/license/new-bsd New BSD License
  8. */
  9. namespace Zend\Stdlib;
  10. use ErrorException;
  11. /**
  12. * ErrorHandler that can be used to catch internal PHP errors
  13. * and convert to an ErrorException instance.
  14. */
  15. abstract class ErrorHandler
  16. {
  17. /**
  18. * Active stack
  19. *
  20. * @var array
  21. */
  22. protected static $stack = array();
  23. /**
  24. * Check if this error handler is active
  25. *
  26. * @return bool
  27. */
  28. public static function started()
  29. {
  30. return (bool) static::getNestedLevel();
  31. }
  32. /**
  33. * Get the current nested level
  34. *
  35. * @return int
  36. */
  37. public static function getNestedLevel()
  38. {
  39. return count(static::$stack);
  40. }
  41. /**
  42. * Starting the error handler
  43. *
  44. * @param int $errorLevel
  45. */
  46. public static function start($errorLevel = \E_WARNING)
  47. {
  48. if (!static::$stack) {
  49. set_error_handler(array(get_called_class(), 'addError'), $errorLevel);
  50. }
  51. static::$stack[] = null;
  52. }
  53. /**
  54. * Stopping the error handler
  55. *
  56. * @param bool $throw Throw the ErrorException if any
  57. * @return null|ErrorException
  58. * @throws ErrorException If an error has been catched and $throw is true
  59. */
  60. public static function stop($throw = false)
  61. {
  62. $errorException = null;
  63. if (static::$stack) {
  64. $errorException = array_pop(static::$stack);
  65. if (!static::$stack) {
  66. restore_error_handler();
  67. }
  68. if ($errorException && $throw) {
  69. throw $errorException;
  70. }
  71. }
  72. return $errorException;
  73. }
  74. /**
  75. * Stop all active handler
  76. *
  77. * @return void
  78. */
  79. public static function clean()
  80. {
  81. if (static::$stack) {
  82. restore_error_handler();
  83. }
  84. static::$stack = array();
  85. }
  86. /**
  87. * Add an error to the stack
  88. *
  89. * @param int $errno
  90. * @param string $errstr
  91. * @param string $errfile
  92. * @param int $errline
  93. * @return void
  94. */
  95. public static function addError($errno, $errstr = '', $errfile = '', $errline = 0)
  96. {
  97. $stack = & static::$stack[count(static::$stack) - 1];
  98. $stack = new ErrorException($errstr, 0, $errno, $errfile, $errline, $stack);
  99. }
  100. }