U
U
ugin_root2019-05-27 08:43:59
symfony
ugin_root, 2019-05-27 08:43:59

How to execute a command programmatically and automatically answer questions?

Within your team, you need to call others and automatically answer the questions asked. Now it's done like this:

$this->getApplication()->get('doctrine:migrations:migrate')->run($input, $output);

As a result, questions are asked by the console itself and have to be answered every time. I'm wondering if there is a way to answer questions automatically.
The console asks me every time:
WARNING! You are about to execute a database migration that could result in schema changes and data loss. Are you sure you wish to continue? (y/n)

And I have to write "y" every time. The command is given as an example, other commands are actually executed.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
Flying, 2019-05-27
@ugin_root

If we are talking about a particular case of this command, then the answer is quite simple and can be easily found in the source texts. This is how the ability to run the migration command is checked, as you can see - the method is used here canExecute(), looking into which you can see that it is controlled by the flag --no-interaction. Moreover, by simply calling help on this command, you could see the answer to your question written in plain text:

Or you can also execute the migration without a warning message which you need to interact with:

    bin/console doctrine:migrations:migrate --no-interaction

If we are talking about a general approach to how to run console commands that require user input, then the answer is quite in the Symfony documentation. If you look at the source texts ConsoleTesterdiscussed in this section, you can see that the main idea is to use a special input. So the solution becomes quite simple:
All the main code for this can, in an obvious way, be peeped into bin/consoleSymfony itself.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question