Skip to content

Commit 082e357

Browse files
committed
Merge branch '7.4' into 8.0
* 7.4: Tweaks [Console] Document timeout functionality for `QuestionHelper`
2 parents 8b7563e + f710171 commit 082e357

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

components/console/helpers/questionhelper.rst

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -324,6 +324,63 @@ the response to a question should allow multiline answers by passing ``true`` to
324324
Multiline questions stop reading user input after receiving an end-of-transmission
325325
control character (``Ctrl-D`` on Unix systems or ``Ctrl-Z`` on Windows).
326326

327+
Setting a Timeout for User Input
328+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
329+
330+
Sometimes, commands can hang if a user takes too long to respond. For example,
331+
if interactive questions are used inside an open database transaction, a delayed
332+
response could leave the transaction open for too long.
333+
334+
You can prevent this by setting a maximum time limit for input using the
335+
:method:`Symfony\\Component\\Console\\Question\\Question::setTimeout` method.
336+
If the user doesn't respond within the specified timeout, a
337+
:class:`Symfony\\Component\\Console\\Exception\\MissingInputException` will be thrown::
338+
339+
use Symfony\Component\Console\Exception\MissingInputException;
340+
use Symfony\Component\Console\Question\Question;
341+
342+
// ...
343+
public function __invoke(InputInterface $input, OutputInterface $output): int
344+
{
345+
// ...
346+
$helper = new QuestionHelper();
347+
348+
$question = new Question('Please enter your answer');
349+
$question->setTimeout(30); // 30 seconds
350+
351+
try {
352+
$answer = $helper->ask($input, $output, $question);
353+
// ... do something with the answer
354+
} catch (MissingInputException $exception) {
355+
$output->writeln('No input received within timeout period.');
356+
// ... handle timeout
357+
}
358+
359+
return Command::SUCCESS;
360+
}
361+
362+
.. note::
363+
364+
The timeout only applies to interactive input streams. For non-interactive
365+
streams (such as pipes or files), the timeout is ignored and the question
366+
behaves normally.
367+
368+
You can also use timeouts with other question types such as
369+
:class:`Symfony\\Component\\Console\\Question\\ConfirmationQuestion` and
370+
:class:`Symfony\\Component\\Console\\Question\\ChoiceQuestion`::
371+
372+
use Symfony\Component\Console\Question\ConfirmationQuestion;
373+
374+
// ...
375+
$question = new ConfirmationQuestion('Do you want to continue?', false);
376+
$question->setTimeout(10); // 10 seconds
377+
378+
$continue = $helper->ask($input, $output, $question);
379+
380+
.. versionadded:: 7.4
381+
382+
The timeout functionality for questions was introduced in Symfony 7.4.
383+
327384
Hiding the User's Response
328385
~~~~~~~~~~~~~~~~~~~~~~~~~~
329386

0 commit comments

Comments
 (0)