ErrorHandler.php 1.9KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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\HttpKernel\Debug;
  11. /**
  12. * ErrorHandler.
  13. *
  14. * @author Fabien Potencier <fabien@symfony.com>
  15. */
  16. class ErrorHandler
  17. {
  18. private $levels = array(
  19. E_WARNING => 'Warning',
  20. E_NOTICE => 'Notice',
  21. E_USER_ERROR => 'User Error',
  22. E_USER_WARNING => 'User Warning',
  23. E_USER_NOTICE => 'User Notice',
  24. E_STRICT => 'Runtime Notice',
  25. E_RECOVERABLE_ERROR => 'Catchable Fatal Error',
  26. E_DEPRECATED => 'Deprecated',
  27. E_USER_DEPRECATED => 'User Deprecated',
  28. );
  29. private $level;
  30. /**
  31. * Register the error handler.
  32. *
  33. * @param integer $level The level at which the conversion to Exception is done (null to use the error_reporting() value and 0 to disable)
  34. *
  35. * @return The registered error handler
  36. */
  37. static public function register($level = null)
  38. {
  39. $handler = new static();
  40. $handler->setLevel($level);
  41. set_error_handler(array($handler, 'handle'));
  42. return $handler;
  43. }
  44. public function setLevel($level)
  45. {
  46. $this->level = null === $level ? error_reporting() : $level;
  47. }
  48. /**
  49. * @throws \ErrorException When error_reporting returns error
  50. */
  51. public function handle($level, $message, $file, $line, $context)
  52. {
  53. if (0 === $this->level) {
  54. return false;
  55. }
  56. if (error_reporting() & $level && $this->level & $level) {
  57. throw new \ErrorException(sprintf('%s: %s in %s line %d', isset($this->levels[$level]) ? $this->levels[$level] : $level, $message, $file, $line));
  58. }
  59. return false;
  60. }
  61. }