diff --git a/components/console/events.rst b/components/console/events.rst index 7183c2e75f7..cf3ab2a0a24 100644 --- a/components/console/events.rst +++ b/components/console/events.rst @@ -155,3 +155,25 @@ Listeners receive a The exit code received in this case is the exception code. .. _`reserved exit codes`: https://www.tldp.org/LDP/abs/html/exitcodes.html + +The ``ConsoleEvents::SIGNAL`` Event +----------------------------------- + +.. versionadded:: 5.2 + + The ``ConsoleSignalEvent`` class was introduced in Symfony 5.2. + +**Typical Purposes**: To handle some signals for all application commands while being executed. + +Listeners receive a +:class:`Symfony\\Component\\Console\\Event\\ConsoleSignalEvent` event:: + + use Symfony\Component\Console\ConsoleEvents; + use Symfony\Component\Console\Event\ConsoleSignalEvent; + + $dispatcher->addListener(ConsoleEvents::SIGNAL, function (ConsoleSignalEvent $event) { + // https://www.php.net/manual/en/pcntl.constants.php + $signal = $event->getHandlingSignal(); + + // ... + }); diff --git a/console.rst b/console.rst index 72e7ea30e0b..e60dcc07b04 100644 --- a/console.rst +++ b/console.rst @@ -427,6 +427,48 @@ call ``setAutoExit(false)`` on it to get the command result in ``CommandTester`` :class:`Symfony\\Component\\Console\\Application ` and extend the normal ``\PHPUnit\Framework\TestCase``. +Command Reacting to Signals +--------------------------- + +.. versionadded:: 5.2 + + The :class:`Symfony\\Component\\Console\\Command\\SignalableCommandInterface` interface + for reacting to signals was introduced in Symfony 5.2. + +You can make your commands react to signals by implementing the ``SignalableCommandInterface`` interface:: + + // ... + use Symfony\Component\Console\Command\Command; + use Symfony\Component\Console\Command\SignalableCommandInterface; + + class CreateUserCommand extends Command implements SignalableCommandInterface + { + // ... + + public function getSubscribedSignals(): array + { + // constants defined by PCNTL extension + // https://www.php.net/manual/en/pcntl.constants.php + return [SIGINT, SIGTERM]; + } + + public function handleSignal(int $signal): void + { + if (SIGINT === $signal) { + // handle SIGINT signal + } + + // handle SIGTERM signal + } + + protected function execute(InputInterface $input, OutputInterface $output): int + { + // ... + + return Command::SUCCESS; + } + } + Logging Command Errors ----------------------