ErrorHandler.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. <?php // phpcs:disable WebimpressCodingStandard.NamingConventions.AbstractClass.Prefix
  2. declare(strict_types=1);
  3. namespace Laminas\Stdlib;
  4. use ErrorException;
  5. use function array_pop;
  6. use function count;
  7. use function restore_error_handler;
  8. use function set_error_handler;
  9. use const E_WARNING;
  10. /**
  11. * ErrorHandler that can be used to catch internal PHP errors
  12. * and convert to an ErrorException instance.
  13. */
  14. abstract class ErrorHandler
  15. {
  16. /**
  17. * Active stack
  18. *
  19. * @var list<ErrorException|null>
  20. */
  21. protected static $stack = [];
  22. /**
  23. * Check if this error handler is active
  24. *
  25. * @return bool
  26. */
  27. public static function started()
  28. {
  29. return (bool) static::getNestedLevel();
  30. }
  31. /**
  32. * Get the current nested level
  33. *
  34. * @return int
  35. */
  36. public static function getNestedLevel()
  37. {
  38. return count(static::$stack);
  39. }
  40. /**
  41. * Starting the error handler
  42. *
  43. * @param int $errorLevel
  44. * @return void
  45. */
  46. public static function start($errorLevel = E_WARNING)
  47. {
  48. if (! static::$stack) {
  49. set_error_handler([static::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 caught 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 = [];
  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. }