SignalRegistry.php 1.5 KB

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