@@ -324,6 +324,63 @@ the response to a question should allow multiline answers by passing ``true`` to
324
324
Multiline questions stop reading user input after receiving an end-of-transmission
325
325
control character (``Ctrl-D `` on Unix systems or ``Ctrl-Z `` on Windows).
326
326
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
+
327
384
Hiding the User's Response
328
385
~~~~~~~~~~~~~~~~~~~~~~~~~~
329
386
0 commit comments