ErrorHandler.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. namespace Symfony\Framework\Debug;
  3. /*
  4. * This file is part of the Symfony framework.
  5. *
  6. * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
  7. *
  8. * This source file is subject to the MIT license that is bundled
  9. * with this source code in the file LICENSE.
  10. */
  11. /**
  12. * ErrorHandler.
  13. *
  14. * @author Fabien Potencier <fabien.potencier@symfony-project.com>
  15. */
  16. class ErrorHandler
  17. {
  18. protected $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. );
  27. protected $level;
  28. /**
  29. * Constructor.
  30. *
  31. * @param integer $level The level at which the conversion to Exception is done (null to use the error_reporting() value and 0 to disable)
  32. */
  33. public function __construct($level = null)
  34. {
  35. $this->level = null === $level ? error_reporting() : $level;
  36. }
  37. public function register()
  38. {
  39. set_error_handler(array($this, 'handle'));
  40. }
  41. /**
  42. * @throws \ErrorException When error_reporting returns error
  43. */
  44. public function handle($level, $message, $file, $line, $context)
  45. {
  46. if (0 === $this->level) {
  47. return false;
  48. }
  49. if (error_reporting() & $level && $this->level & $level) {
  50. throw new \ErrorException(sprintf('%s: %s in %s line %d', isset($this->levels[$level]) ? $this->levels[$level] : $level, $message, $file, $line));
  51. }
  52. return false;
  53. }
  54. }