Silencer.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. /**
  13. * Temporarily suppress PHP error reporting, usually warnings and below.
  14. *
  15. * @author Niels Keurentjes <niels.keurentjes@omines.com>
  16. */
  17. class Silencer
  18. {
  19. /**
  20. * @var int[] Unpop stack
  21. */
  22. private static $stack = array();
  23. /**
  24. * Suppresses given mask or errors.
  25. *
  26. * @param int|null $mask Error levels to suppress, default value NULL indicates all warnings and below.
  27. * @return int The old error reporting level.
  28. */
  29. public static function suppress($mask = null)
  30. {
  31. if (!isset($mask)) {
  32. $mask = E_WARNING | E_NOTICE | E_USER_WARNING | E_USER_NOTICE | E_DEPRECATED | E_USER_DEPRECATED | E_STRICT;
  33. }
  34. $old = error_reporting();
  35. self::$stack[] = $old;
  36. error_reporting($old & ~$mask);
  37. return $old;
  38. }
  39. /**
  40. * Restores a single state.
  41. */
  42. public static function restore()
  43. {
  44. if (!empty(self::$stack)) {
  45. error_reporting(array_pop(self::$stack));
  46. }
  47. }
  48. /**
  49. * Calls a specified function while silencing warnings and below.
  50. *
  51. * Future improvement: when PHP requirements are raised add Callable type hint (5.4) and variadic parameters (5.6)
  52. *
  53. * @param callable $callable Function to execute.
  54. * @throws \Exception Any exceptions from the callback are rethrown.
  55. * @return mixed Return value of the callback.
  56. */
  57. public static function call($callable /*, ...$parameters */)
  58. {
  59. try {
  60. self::suppress();
  61. $result = call_user_func_array($callable, array_slice(func_get_args(), 1));
  62. self::restore();
  63. return $result;
  64. } catch (\Exception $e) {
  65. // Use a finally block for this when requirements are raised to PHP 5.5
  66. self::restore();
  67. throw $e;
  68. }
  69. }
  70. }