Skip to content

Commit 35027e4

Browse files
author
Thomas Ploch
committed
[WCM] Skip console commands from event listeners
| Q | A | ------------- | --- | Doc fix? | no | New docs? | yes (symfony/symfony#9235) | Applies to | master | Fixed tickets | none
1 parent 6751a07 commit 35027e4

File tree

1 file changed

+36
-2
lines changed

1 file changed

+36
-2
lines changed

components/console/events.rst

Lines changed: 36 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,8 @@ The ``ConsoleEvents::COMMAND`` Event
2424
------------------------------------
2525

2626
**Typical Purposes**: Doing something before any command is run (like logging
27-
which command is going to be executed), or displaying something about the event
28-
to be executed.
27+
which command is going to be executed), or displaying something about the event to be
28+
executed.
2929

3030
Just before executing any command, the ``ConsoleEvents::COMMAND`` event is
3131
dispatched. Listeners receive a
@@ -51,6 +51,39 @@ 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 codes reserved
65+
for the console commands to conform with the C/C++ standard (see
66+
http://www.tldp.org/LDP/abs/html/exitcodes.html for more information).::
67+
68+
use Symfony\Component\Console\Event\ConsoleCommandEvent;
69+
use Symfony\Component\Console\ConsoleEvents;
70+
71+
$dispatcher->addListener(ConsoleEvents::COMMAND, function (ConsoleCommandEvent $event) {
72+
// get the command to be executed
73+
$command = $event->getCommand();
74+
75+
// ... check if the command can be executed
76+
77+
// disable the command, this will result in the command being skipped
78+
// and code 113 being returned from the Application
79+
$event->disableCommand();
80+
81+
// it is possible to enable the command in a later listener
82+
if (!$event->commandShouldRun()) {
83+
$event->enableCommand();
84+
}
85+
});
86+
5487
The ``ConsoleEvents::TERMINATE`` Event
5588
--------------------------------------
5689

@@ -118,3 +151,4 @@ Listeners receive a
118151
// change the exception to another one
119152
$event->setException(new \LogicException('Caught exception', $exitCode, $event->getException()));
120153
});
154+

0 commit comments

Comments
 (0)