Skip to content

Commit 23f790a

Browse files
committed
feature #4058 Skip console commands from event listeners (tPl0ch)
This PR was merged into the master branch. Discussion ---------- Skip console commands from event listeners | Q | A | ------------- | --- | Doc fix? | no | New docs? | yes (symfony/symfony#9235) | Applies to | master | Fixed tickets | none Commits ------- cb508f7 [WCM] Skip console commands from event listeners
2 parents 4b98d48 + cb508f7 commit 23f790a

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

components/console/events.rst

+35
Original file line numberDiff line numberDiff line change
@@ -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+
5488
The ``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

Comments
 (0)