ErrorHandler.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. /*
  3. * This file is part of Composer.
  4. *
  5. * (c) Nils Adermann <naderman@naderman.de>
  6. * Jordi Boggiano <j.boggiano@seld.be>
  7. *
  8. * For the full copyright and license information, please view the LICENSE
  9. * file that was distributed with this source code.
  10. */
  11. namespace Composer\Util;
  12. use Composer\IO\IOInterface;
  13. /**
  14. * Convert PHP errors into exceptions
  15. *
  16. * @author Artem Lopata <biozshock@gmail.com>
  17. */
  18. class ErrorHandler
  19. {
  20. private static $io;
  21. /**
  22. * Error handler
  23. *
  24. * @param int $level Level of the error raised
  25. * @param string $message Error message
  26. * @param string $file Filename that the error was raised in
  27. * @param int $line Line number the error was raised at
  28. *
  29. * @static
  30. * @throws \ErrorException
  31. * @return bool
  32. */
  33. public static function handle($level, $message, $file, $line)
  34. {
  35. // error code is not included in error_reporting
  36. if (!(error_reporting() & $level)) {
  37. return;
  38. }
  39. if (filter_var(ini_get('xdebug.scream'), FILTER_VALIDATE_BOOLEAN)) {
  40. $message .= "\n\nWarning: You have xdebug.scream enabled, the warning above may be".
  41. "\na legitimately suppressed error that you were not supposed to see.";
  42. }
  43. if ($level !== E_DEPRECATED && $level !== E_USER_DEPRECATED) {
  44. throw new \ErrorException($message, 0, $level, $file, $line);
  45. }
  46. if (self::$io) {
  47. self::$io->writeError('<warning>Deprecation Notice: '.$message.' in '.$file.':'.$line.'</warning>');
  48. if (self::$io->isVerbose()) {
  49. self::$io->writeError('<warning>Stack trace:</warning>');
  50. self::$io->writeError(array_filter(array_map(function ($a) {
  51. if (isset($a['line'], $a['file'])) {
  52. return '<warning> '.$a['file'].':'.$a['line'].'</warning>';
  53. }
  54. return null;
  55. }, array_slice(debug_backtrace(), 2))));
  56. }
  57. }
  58. return true;
  59. }
  60. /**
  61. * Register error handler.
  62. *
  63. * @param IOInterface|null $io
  64. */
  65. public static function register(IOInterface $io = null)
  66. {
  67. set_error_handler(array(__CLASS__, 'handle'));
  68. error_reporting(E_ALL | E_STRICT);
  69. self::$io = $io;
  70. }
  71. }