ErrorHandler.php 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Debug;
  11. use Symfony\Component\Debug\Exception\FatalErrorException;
  12. use Symfony\Component\Debug\Exception\ContextErrorException;
  13. use Psr\Log\LoggerInterface;
  14. /**
  15. * ErrorHandler.
  16. *
  17. * @author Fabien Potencier <fabien@symfony.com>
  18. * @author Konstantin Myakshin <koc-dp@yandex.ru>
  19. */
  20. class ErrorHandler
  21. {
  22. const TYPE_DEPRECATION = -100;
  23. private $levels = array(
  24. E_WARNING => 'Warning',
  25. E_NOTICE => 'Notice',
  26. E_USER_ERROR => 'User Error',
  27. E_USER_WARNING => 'User Warning',
  28. E_USER_NOTICE => 'User Notice',
  29. E_STRICT => 'Runtime Notice',
  30. E_RECOVERABLE_ERROR => 'Catchable Fatal Error',
  31. E_DEPRECATED => 'Deprecated',
  32. E_USER_DEPRECATED => 'User Deprecated',
  33. E_ERROR => 'Error',
  34. E_CORE_ERROR => 'Core Error',
  35. E_COMPILE_ERROR => 'Compile Error',
  36. E_PARSE => 'Parse',
  37. );
  38. private $level;
  39. private $reservedMemory;
  40. private $displayErrors;
  41. /**
  42. * @var LoggerInterface[] Loggers for channels
  43. */
  44. private static $loggers = array();
  45. /**
  46. * Registers the error handler.
  47. *
  48. * @param integer $level The level at which the conversion to Exception is done (null to use the error_reporting() value and 0 to disable)
  49. * @param Boolean $displayErrors Display errors (for dev environment) or just log they (production usage)
  50. *
  51. * @return The registered error handler
  52. */
  53. public static function register($level = null, $displayErrors = true)
  54. {
  55. $handler = new static();
  56. $handler->setLevel($level);
  57. $handler->setDisplayErrors($displayErrors);
  58. ini_set('display_errors', 0);
  59. set_error_handler(array($handler, 'handle'));
  60. register_shutdown_function(array($handler, 'handleFatal'));
  61. $handler->reservedMemory = str_repeat('x', 10240);
  62. return $handler;
  63. }
  64. public function setLevel($level)
  65. {
  66. $this->level = null === $level ? error_reporting() : $level;
  67. }
  68. public function setDisplayErrors($displayErrors)
  69. {
  70. $this->displayErrors = $displayErrors;
  71. }
  72. public static function setLogger(LoggerInterface $logger, $channel = 'deprecation')
  73. {
  74. self::$loggers[$channel] = $logger;
  75. }
  76. /**
  77. * @throws ContextErrorException When error_reporting returns error
  78. */
  79. public function handle($level, $message, $file = 'unknown', $line = 0, $context = array())
  80. {
  81. if (0 === $this->level) {
  82. return false;
  83. }
  84. if ($level & (E_USER_DEPRECATED | E_DEPRECATED)) {
  85. if (isset(self::$loggers['deprecation'])) {
  86. if (version_compare(PHP_VERSION, '5.4', '<')) {
  87. $stack = array_map(
  88. function ($row) {
  89. unset($row['args']);
  90. return $row;
  91. },
  92. array_slice(debug_backtrace(false), 0, 10)
  93. );
  94. } else {
  95. $stack = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 10);
  96. }
  97. self::$loggers['deprecation']->warning($message, array('type' => self::TYPE_DEPRECATION, 'stack' => $stack));
  98. }
  99. return true;
  100. }
  101. if ($this->displayErrors && error_reporting() & $level && $this->level & $level) {
  102. // make sure the ContextErrorException class is loaded (https://bugs.php.net/bug.php?id=65322)
  103. if (!class_exists('Symfony\Component\Debug\Exception\ContextErrorException')) {
  104. require __DIR__.'/Exception/ContextErrorException.php';
  105. }
  106. throw new ContextErrorException(sprintf('%s: %s in %s line %d', isset($this->levels[$level]) ? $this->levels[$level] : $level, $message, $file, $line), 0, $level, $file, $line, $context);
  107. }
  108. return false;
  109. }
  110. public function handleFatal()
  111. {
  112. if (null === $error = error_get_last()) {
  113. return;
  114. }
  115. unset($this->reservedMemory);
  116. $type = $error['type'];
  117. if (0 === $this->level || !in_array($type, array(E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_PARSE))) {
  118. return;
  119. }
  120. if (isset(self::$loggers['emergency'])) {
  121. $fatal = array(
  122. 'type' => $type,
  123. 'file' => $error['file'],
  124. 'line' => $error['line'],
  125. );
  126. self::$loggers['emergency']->emerg($error['message'], $fatal);
  127. }
  128. if (!$this->displayErrors) {
  129. return;
  130. }
  131. // get current exception handler
  132. $exceptionHandler = set_exception_handler(function() {});
  133. restore_exception_handler();
  134. if (is_array($exceptionHandler) && $exceptionHandler[0] instanceof ExceptionHandler) {
  135. $level = isset($this->levels[$type]) ? $this->levels[$type] : $type;
  136. $message = sprintf('%s: %s in %s line %d', $level, $error['message'], $error['file'], $error['line']);
  137. $exception = new FatalErrorException($message, 0, $type, $error['file'], $error['line']);
  138. $exceptionHandler[0]->handle($exception);
  139. }
  140. }
  141. }