Skip to content

Commit 1e7e1ac

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 1e7e1ac

File tree

1 file changed

+26
-2
lines changed

1 file changed

+26
-2
lines changed

components/console/events.rst

Lines changed: 26 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,29 @@ dispatched. Listeners receive a
5151
$application = $command->getApplication();
5252
});
5353

54+
.. versionadded:: 2.6
55+
From Symfony 2.6 you can disable commands inside the listeners. The application
56+
will the return the code `113` (defined in ``ConsoleCommandEvent::RETURN_CODE_DISABLED``)::
57+
58+
use Symfony\Component\Console\Event\ConsoleCommandEvent;
59+
use Symfony\Component\Console\ConsoleEvents;
60+
61+
$dispatcher->addListener(ConsoleEvents::COMMAND, function (ConsoleCommandEvent $event) {
62+
// get the command to be executed
63+
$command = $event->getCommand();
64+
65+
// ...check if the command can be executed
66+
67+
// disable the command, this will result in the command being skipped
68+
// and code 113 being returned from the Application
69+
$event->disableCommand();
70+
71+
// it is possible to enable the command in a later listener
72+
if (!$event->commandShouldRun()) {
73+
$event->enableCommand();
74+
}
75+
});
76+
5477
The ``ConsoleEvents::TERMINATE`` Event
5578
--------------------------------------
5679

@@ -118,3 +141,4 @@ Listeners receive a
118141
// change the exception to another one
119142
$event->setException(new \LogicException('Caught exception', $exitCode, $event->getException()));
120143
});
144+

0 commit comments

Comments
 (0)