@@ -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
+ .. versionadded :: 7.4
331
+
332
+ The timeout functionality for questions was introduced in Symfony 7.4.
333
+
334
+ You can set a maximum time limit for user input by 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 timeout
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
+ This is particularly useful when you have interactive questions inside database
363
+ transactions or other time-sensitive operations where hanging indefinitely
364
+ could cause problems.
365
+
366
+ .. note ::
367
+
368
+ The timeout only applies to interactive input streams. For non-interactive
369
+ streams (like pipes or files), the timeout setting is ignored and the
370
+ question behaves normally.
371
+
372
+ You can also use timeouts with other question types such as
373
+ :class: `Symfony\\ Component\\ Console\\ Question\\ ConfirmationQuestion ` and
374
+ :class: `Symfony\\ Component\\ Console\\ Question\\ ChoiceQuestion `::
375
+
376
+ use Symfony\Component\Console\Question\ConfirmationQuestion;
377
+
378
+ // ...
379
+ $question = new ConfirmationQuestion('Do you want to continue?', false);
380
+ $question->setTimeout(10); // 10 seconds timeout
381
+
382
+ $continue = $helper->ask($input, $output, $question);
383
+
327
384
Hiding the User's Response
328
385
~~~~~~~~~~~~~~~~~~~~~~~~~~
329
386
0 commit comments