SignalRegistry.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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\Console\SignalRegistry;
  11. final class SignalRegistry
  12. {
  13. /**
  14. * @var mixed[]
  15. */
  16. private $signalHandlers = [];
  17. public function __construct()
  18. {
  19. if (\function_exists('pcntl_async_signals')) {
  20. pcntl_async_signals(true);
  21. }
  22. }
  23. public function register(int $signal, callable $signalHandler)
  24. {
  25. if (!isset($this->signalHandlers[$signal])) {
  26. $previousCallback = pcntl_signal_get_handler($signal);
  27. if (\is_callable($previousCallback)) {
  28. $this->signalHandlers[$signal][] = $previousCallback;
  29. }
  30. }
  31. $this->signalHandlers[$signal][] = $signalHandler;
  32. pcntl_signal($signal, \Closure::fromCallable([$this, 'handle']));
  33. }
  34. public static function isSupported()
  35. {
  36. return \function_exists('pcntl_signal');
  37. }
  38. /**
  39. * @internal
  40. */
  41. public function handle(int $signal)
  42. {
  43. $count = \count($this->signalHandlers[$signal]);
  44. foreach ($this->signalHandlers[$signal] as $i => $signalHandler) {
  45. $hasNext = $i !== $count - 1;
  46. $signalHandler($signal, $hasNext);
  47. }
  48. }
  49. }