@@ -51,6 +51,40 @@ dispatched. Listeners receive a
5151 $application = $command->getApplication();
5252 });
5353
54+ Disable Commands inside Listeners
55+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
56+
57+ .. versionadded :: 2.6
58+ Disabling commands inside listeners was introduced in Symfony 2.6.
59+
60+ Using the
61+ :method: `Symfony\\ Component\\ Console\\ Event\\ ConsoleCommandEvent::disableCommand `
62+ method, you can disable a command inside a listener. The application
63+ will then not execute the command but return the code `113 ` (defined in
64+ ``ConsoleCommandEvent::RETURN_CODE_DISABLED ``), which is one of the
65+ `reserved exit codes `_ for console commands to conform with the C/C++ standard.::
66+
67+ use Symfony\Component\Console\Event\ConsoleCommandEvent;
68+ use Symfony\Component\Console\ConsoleEvents;
69+
70+ $dispatcher->addListener(ConsoleEvents::COMMAND, function (ConsoleCommandEvent $event) {
71+ // get the command to be executed
72+ $command = $event->getCommand();
73+
74+ // ... check if the command can be executed
75+
76+ // disable the command, this will result in the command being skipped
77+ // and code 113 being returned from the Application
78+ $event->disableCommand();
79+
80+ // it is possible to enable the command in a later listener
81+ if (!$event->commandShouldRun()) {
82+ $event->enableCommand();
83+ }
84+ });
85+
86+ .. _`reserved exit codes` : http://www.tldp.org/LDP/abs/html/exitcodes.html
87+
5488The ``ConsoleEvents::TERMINATE `` Event
5589--------------------------------------
5690
@@ -118,3 +152,4 @@ Listeners receive a
118152 // change the exception to another one
119153 $event->setException(new \LogicException('Caught exception', $exitCode, $event->getException()));
120154 });
155+
0 commit comments