Debian Codegraph @

vendor/symfony/console/Helper/QuestionHelper.php

raw
1 <?php
2
3 /*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <[email protected]>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Symfony\Component\Console\Helper;
13
14 use Symfony\Component\Console\Cursor;
15 use Symfony\Component\Console\Exception\MissingInputException;
16 use Symfony\Component\Console\Exception\RuntimeException;
17 use Symfony\Component\Console\Formatter\OutputFormatter;
18 use Symfony\Component\Console\Formatter\OutputFormatterStyle;
19 use Symfony\Component\Console\Input\InputInterface;
20 use Symfony\Component\Console\Input\StreamableInputInterface;
21 use Symfony\Component\Console\Output\ConsoleOutputInterface;
22 use Symfony\Component\Console\Output\ConsoleSectionOutput;
23 use Symfony\Component\Console\Output\OutputInterface;
24 use Symfony\Component\Console\Question\ChoiceQuestion;
25 use Symfony\Component\Console\Question\Question;
26 use Symfony\Component\Console\Terminal;
27
28 use function Symfony\Component\String\s;
29
30 /**
31 * The QuestionHelper class provides helpers to interact with the user.
32 *
33 * @author Fabien Potencier <[email protected]>
34 */
35 class QuestionHelper extends Helper
36 {
37 private static bool $stty = true;
38 private static bool $stdinIsInteractive;
39
40 /**
41 * Asks a question to the user.
42 *
43 * @return mixed The user answer
44 *
45 * @throws RuntimeException If there is no data to read in the input stream
46 */
47 public function ask(InputInterface $input, OutputInterface $output, Question $question): mixed
48 {
49 if ($output instanceof ConsoleOutputInterface) {
50 $output = $output->getErrorOutput();
51 }
52
53 if (!$input->isInteractive()) {
54 return $this->getDefaultAnswer($question);
55 }
56
57 $inputStream = $input instanceof StreamableInputInterface ? $input->getStream() : null;
58 $inputStream ??= \STDIN;
59
60 try {
61 if (!$question->getValidator()) {
62 return $this->doAsk($inputStream, $output, $question);
63 }
64
65 $interviewer = fn () => $this->doAsk($inputStream, $output, $question);
66
67 return $this->validateAttempts($interviewer, $output, $question);
68 } catch (MissingInputException $exception) {
69 $input->setInteractive(false);
70
71 if (null === $fallbackOutput = $this->getDefaultAnswer($question)) {
72 throw $exception;
73 }
74
75 return $fallbackOutput;
76 }
77 }
78
79 public function getName(): string
80 {
81 return 'question';
82 }
83
84 /**
85 * Prevents usage of stty.
86 */
87 public static function disableStty(): void
88 {
89 self::$stty = false;
90 }
91
92 /**
93 * Asks the question to the user.
94 *
95 * @param resource $inputStream
96 *
97 * @throws RuntimeException In case the fallback is deactivated and the response cannot be hidden
98 */
99 private function doAsk($inputStream, OutputInterface $output, Question $question): mixed
100 {
101 $this->writePrompt($output, $question);
102
103 $autocomplete = $question->getAutocompleterCallback();
104
105 if (null === $autocomplete || !self::$stty || !Terminal::hasSttyAvailable()) {
106 $ret = false;
107 if ($question->isHidden()) {
108 try {
109 $hiddenResponse = $this->getHiddenResponse($output, $inputStream, $question->isTrimmable());
110 $ret = $question->isTrimmable() ? trim($hiddenResponse) : $hiddenResponse;
111 } catch (RuntimeException $e) {
112 if (!$question->isHiddenFallback()) {
113 throw $e;
114 }
115 }
116 }
117
118 if (false === $ret) {
119 $isBlocked = stream_get_meta_data($inputStream)['blocked'] ?? true;
120
121 if (!$isBlocked) {
122 stream_set_blocking($inputStream, true);
123 }
124
125 $ret = $this->readInput($inputStream, $question);
126
127 if (!$isBlocked) {
128 stream_set_blocking($inputStream, false);
129 }
130
131 if (false === $ret) {
132 throw new MissingInputException('Aborted.');
133 }
134 if ($question->isTrimmable()) {
135 $ret = trim($ret);
136 }
137 }
138 } else {
139 $autocomplete = $this->autocomplete($output, $question, $inputStream, $autocomplete);
140 $ret = $question->isTrimmable() ? trim($autocomplete) : $autocomplete;
141 }
142
143 if ($output instanceof ConsoleSectionOutput) {
144 $output->addContent(''); // add EOL to the question
145 $output->addContent($ret);
146 }
147
148 $ret = \strlen($ret) > 0 ? $ret : $question->getDefault();
149
150 if ($normalizer = $question->getNormalizer()) {
151 return $normalizer($ret);
152 }
153
154 return $ret;
155 }
156
157 private function getDefaultAnswer(Question $question): mixed
158 {
159 $default = $question->getDefault();
160
161 if (null === $default) {
162 return $default;
163 }
164
165 if ($validator = $question->getValidator()) {
166 return \call_user_func($validator, $default);
167 } elseif ($question instanceof ChoiceQuestion) {
168 $choices = $question->getChoices();
169
170 if (!$question->isMultiselect()) {
171 return $choices[$default] ?? $default;
172 }
173
174 $default = explode(',', $default);
175 foreach ($default as $k => $v) {
176 $v = $question->isTrimmable() ? trim($v) : $v;
177 $default[$k] = $choices[$v] ?? $v;
178 }
179 }
180
181 return $default;
182 }
183
184 /**
185 * Outputs the question prompt.
186 */
187 protected function writePrompt(OutputInterface $output, Question $question): void
188 {
189 $message = $question->getQuestion();
190
191 if ($question instanceof ChoiceQuestion) {
192 $output->writeln(array_merge([
193 $question->getQuestion(),
194 ], $this->formatChoiceQuestionChoices($question, 'info')));
195
196 $message = $question->getPrompt();
197 }
198
199 $output->write($message);
200 }
201
202 /**
203 * @return string[]
204 */
205 protected function formatChoiceQuestionChoices(ChoiceQuestion $question, string $tag): array
206 {
207 $messages = [];
208
209 $maxWidth = max(array_map([__CLASS__, 'width'], array_keys($choices = $question->getChoices())));
210
211 foreach ($choices as $key => $value) {
212 $padding = str_repeat(' ', $maxWidth - self::width($key));
213
214 $messages[] = \sprintf(" [<$tag>%s$padding</$tag>] %s", $key, $value);
215 }
216
217 return $messages;
218 }
219
220 /**
221 * Outputs an error message.
222 */
223 protected function writeError(OutputInterface $output, \Exception $error): void
224 {
225 if (null !== $this->getHelperSet() && $this->getHelperSet()->has('formatter')) {
226 $message = $this->getHelperSet()->get('formatter')->formatBlock($error->getMessage(), 'error');
227 } else {
228 $message = '<error>'.$error->getMessage().'</error>';
229 }
230
231 $output->writeln($message);
232 }
233
234 /**
235 * Autocompletes a question.
236 *
237 * @param resource $inputStream
238 * @param callable(string):string[] $autocomplete
239 */
240 private function autocomplete(OutputInterface $output, Question $question, $inputStream, callable $autocomplete): string
241 {
242 $cursor = new Cursor($output, $inputStream);
243
244 $fullChoice = '';
245 $ret = '';
246
247 $i = 0;
248 $ofs = -1;
249 $matches = $autocomplete($ret);
250 $numMatches = \count($matches);
251 $inputHelper = new TerminalInputHelper($inputStream);
252
253 // Disable icanon (so we can fread each keypress) and echo (we'll do echoing here instead)
254 shell_exec('stty -icanon -echo');
255
256 // Add highlighted text style
257 $output->getFormatter()->setStyle('hl', new OutputFormatterStyle('black', 'white'));
258
259 // Read a keypress
260 while (!feof($inputStream)) {
261 $inputHelper->waitForInput();
262 $c = fread($inputStream, 1);
263
264 // as opposed to fgets(), fread() returns an empty string when the stream content is empty, not false.
265 if (false === $c || ('' === $ret && '' === $c && null === $question->getDefault())) {
266 // Restore the terminal so it behaves normally again
267 $inputHelper->finish();
268 throw new MissingInputException('Aborted while asking: '.$question->getQuestion());
269 } elseif ("\177" === $c) { // Backspace Character
270 if (0 === $numMatches && 0 !== $i) {
271 --$i;
272 $cursor->moveLeft(s($fullChoice)->slice(-1)->width(false));
273
274 $fullChoice = self::substr($fullChoice, 0, $i);
275 }
276
277 if (0 === $i) {
278 $ofs = -1;
279 $matches = $autocomplete($ret);
280 $numMatches = \count($matches);
281 } else {
282 $numMatches = 0;
283 }
284
285 // Pop the last character off the end of our string
286 $ret = self::substr($ret, 0, $i);
287 } elseif ("\033" === $c) {
288 // Did we read an escape sequence?
289 $c .= fread($inputStream, 2);
290
291 // A = Up Arrow. B = Down Arrow
292 if (isset($c[2]) && ('A' === $c[2] || 'B' === $c[2])) {
293 if ('A' === $c[2] && -1 === $ofs) {
294 $ofs = 0;
295 }
296
297 if (0 === $numMatches) {
298 continue;
299 }
300
301 $ofs += ('A' === $c[2]) ? -1 : 1;
302 $ofs = ($numMatches + $ofs) % $numMatches;
303 }
304 } elseif ('' === $c || \ord($c) < 32) {
305 if ("\t" === $c || "\n" === $c) {
306 if ($numMatches > 0 && -1 !== $ofs) {
307 $ret = (string) $matches[$ofs];
308 // Echo out remaining chars for current match
309 $remainingCharacters = substr($ret, \strlen($this->mostRecentlyEnteredValue($fullChoice)));
310 $output->write($remainingCharacters);
311 $fullChoice .= $remainingCharacters;
312 $i = (false === $encoding = mb_detect_encoding($fullChoice, null, true)) ? \strlen($fullChoice) : mb_strlen($fullChoice, $encoding);
313
314 $matches = array_filter(
315 $autocomplete($ret),
316 static fn ($match) => '' === $ret || str_starts_with($match, $ret)
317 );
318 $numMatches = \count($matches);
319 $ofs = -1;
320 }
321
322 if ("\n" === $c) {
323 $output->write($c);
324 break;
325 }
326
327 $numMatches = 0;
328 }
329
330 continue;
331 } else {
332 if ("\x80" <= $c) {
333 $c .= fread($inputStream, ["\xC0" => 1, "\xD0" => 1, "\xE0" => 2, "\xF0" => 3][$c & "\xF0"]);
334 }
335
336 $output->write($c);
337 $ret .= $c;
338 $fullChoice .= $c;
339 ++$i;
340
341 $tempRet = $ret;
342
343 if ($question instanceof ChoiceQuestion && $question->isMultiselect()) {
344 $tempRet = $this->mostRecentlyEnteredValue($fullChoice);
345 }
346
347 $numMatches = 0;
348 $ofs = 0;
349
350 foreach ($autocomplete($ret) as $value) {
351 // If typed characters match the beginning chunk of value (e.g. [AcmeDe]moBundle)
352 if (str_starts_with($value, $tempRet)) {
353 $matches[$numMatches++] = $value;
354 }
355 }
356 }
357
358 $cursor->clearLineAfter();
359
360 if ($numMatches > 0 && -1 !== $ofs) {
361 $cursor->savePosition();
362 // Write highlighted text, complete the partially entered response
363 $charactersEntered = \strlen($this->mostRecentlyEnteredValue($fullChoice));
364 $output->write('<hl>'.OutputFormatter::escapeTrailingBackslash(substr($matches[$ofs], $charactersEntered)).'</hl>');
365 $cursor->restorePosition();
366 }
367 }
368
369 // Restore the terminal so it behaves normally again
370 $inputHelper->finish();
371
372 return $fullChoice;
373 }
374
375 private function mostRecentlyEnteredValue(string $entered): string
376 {
377 // Determine the most recent value that the user entered
378 if (!str_contains($entered, ',')) {
379 return $entered;
380 }
381
382 if (false === $lastCommaPos = strrpos($entered, ',')) {
383 return $entered;
384 }
385
386 $lastChoice = trim(substr($entered, $lastCommaPos + 1));
387
388 return '' !== $lastChoice ? $lastChoice : $entered;
389 }
390
391 /**
392 * Gets a hidden response from user.
393 *
394 * @param resource $inputStream The handler resource
395 * @param bool $trimmable Is the answer trimmable
396 *
397 * @throws RuntimeException In case the fallback is deactivated and the response cannot be hidden
398 */
399 private function getHiddenResponse(OutputInterface $output, $inputStream, bool $trimmable = true): string
400 {
401 if ('\\' === \DIRECTORY_SEPARATOR) {
402 $exe = __DIR__.'/../Resources/bin/hiddeninput.exe';
403
404 // handle code running from a phar
405 if (str_starts_with(__FILE__, 'phar:')) {
406 $tmpExe = sys_get_temp_dir().'/hiddeninput.exe';
407 copy($exe, $tmpExe);
408 $exe = $tmpExe;
409 }
410
411 $sExec = shell_exec('"'.$exe.'"');
412 $value = $trimmable ? rtrim($sExec) : $sExec;
413 $output->writeln('');
414
415 if (isset($tmpExe)) {
416 unlink($tmpExe);
417 }
418
419 return $value;
420 }
421
422 $inputHelper = null;
423
424 if (self::$stty && Terminal::hasSttyAvailable()) {
425 $inputHelper = new TerminalInputHelper($inputStream);
426 shell_exec('stty -echo');
427 } elseif ($this->isInteractiveInput($inputStream)) {
428 throw new RuntimeException('Unable to hide the response.');
429 }
430
431 $value = $this->doReadInput($inputStream, helper: $inputHelper);
432
433 if (4095 === \strlen($value)) {
434 $errOutput = $output instanceof ConsoleOutputInterface ? $output->getErrorOutput() : $output;
435 $errOutput->warning('The value was possibly truncated by your shell or terminal emulator');
436 }
437
438 // Restore the terminal so it behaves normally again
439 $inputHelper?->finish();
440
441 if ($trimmable) {
442 $value = trim($value);
443 }
444 $output->writeln('');
445
446 return $value;
447 }
448
449 /**
450 * Validates an attempt.
451 *
452 * @param callable $interviewer A callable that will ask for a question and return the result
453 *
454 * @throws \Exception In case the max number of attempts has been reached and no valid response has been given
455 */
456 private function validateAttempts(callable $interviewer, OutputInterface $output, Question $question): mixed
457 {
458 $error = null;
459 $attempts = $question->getMaxAttempts();
460
461 while (null === $attempts || $attempts--) {
462 if (null !== $error) {
463 $this->writeError($output, $error);
464 }
465
466 try {
467 return $question->getValidator()($interviewer());
468 } catch (MissingInputException $e) {
469 throw $error ?? $e;
470 } catch (RuntimeException $e) {
471 throw $e;
472 } catch (\Exception $error) {
473 }
474 }
475
476 throw $error;
477 }
478
479 private function isInteractiveInput($inputStream): bool
480 {
481 if ('php://stdin' !== (stream_get_meta_data($inputStream)['uri'] ?? null)) {
482 return false;
483 }
484
485 if (isset(self::$stdinIsInteractive)) {
486 return self::$stdinIsInteractive;
487 }
488
489 return self::$stdinIsInteractive = @stream_isatty(fopen('php://stdin', 'r'));
490 }
491
492 /**
493 * Reads one or more lines of input and returns what is read.
494 *
495 * @param resource $inputStream The handler resource
496 * @param Question $question The question being asked
497 */
498 private function readInput($inputStream, Question $question): string|false
499 {
500 if (null !== $question->getTimeout() && $this->isInteractiveInput($inputStream)) {
501 $read = [$inputStream];
502 $write = null;
503 $except = null;
504 $timeoutSeconds = $question->getTimeout();
505 $changedStreams = stream_select($read, $write, $except, $timeoutSeconds);
506
507 if (0 === $changedStreams) {
508 throw new MissingInputException(\sprintf('Timed out after waiting for input for %d second%s.', $timeoutSeconds, 1 === $timeoutSeconds ? '' : 's'));
509 }
510 }
511
512 if (!$question->isMultiline()) {
513 $cp = $this->setIOCodepage();
514 $ret = $this->doReadInput($inputStream);
515
516 return $this->resetIOCodepage($cp, $ret);
517 }
518
519 $multiLineStreamReader = $this->cloneInputStream($inputStream);
520 if (null === $multiLineStreamReader) {
521 return false;
522 }
523
524 $cp = $this->setIOCodepage();
525 $ret = $this->doReadInput($multiLineStreamReader, "\x4");
526
527 if (stream_get_meta_data($inputStream)['seekable']) {
528 fseek($inputStream, ftell($multiLineStreamReader));
529 }
530
531 return $this->resetIOCodepage($cp, $ret);
532 }
533
534 private function setIOCodepage(): int
535 {
536 if (\function_exists('sapi_windows_cp_set')) {
537 $cp = sapi_windows_cp_get();
538 sapi_windows_cp_set(sapi_windows_cp_get('oem'));
539
540 return $cp;
541 }
542
543 return 0;
544 }
545
546 /**
547 * Sets console I/O to the specified code page and converts the user input.
548 */
549 private function resetIOCodepage(int $cp, string|false $input): string|false
550 {
551 if (0 !== $cp) {
552 sapi_windows_cp_set($cp);
553
554 if (false !== $input && '' !== $input) {
555 $input = sapi_windows_cp_conv(sapi_windows_cp_get('oem'), $cp, $input);
556 }
557 }
558
559 return $input;
560 }
561
562 /**
563 * Clones an input stream in order to act on one instance of the same
564 * stream without affecting the other instance.
565 *
566 * @param resource $inputStream The handler resource
567 *
568 * @return resource|null The cloned resource, null in case it could not be cloned
569 */
570 private function cloneInputStream($inputStream)
571 {
572 $streamMetaData = stream_get_meta_data($inputStream);
573 $seekable = $streamMetaData['seekable'] ?? false;
574 $mode = $streamMetaData['mode'] ?? 'rb';
575 $uri = $streamMetaData['uri'] ?? null;
576
577 if (null === $uri) {
578 return null;
579 }
580
581 $cloneStream = fopen($uri, $mode);
582
583 // For seekable and writable streams, add all the same data to the
584 // cloned stream and then seek to the same offset.
585 if (true === $seekable && !\in_array($mode, ['r', 'rb', 'rt'], true)) {
586 $offset = ftell($inputStream);
587 rewind($inputStream);
588 stream_copy_to_stream($inputStream, $cloneStream);
589 fseek($inputStream, $offset);
590 fseek($cloneStream, $offset);
591 }
592
593 return $cloneStream;
594 }
595
596 /**
597 * @param resource $inputStream
598 */
599 private function doReadInput($inputStream, ?string $exitChar = null, ?TerminalInputHelper $helper = null): string
600 {
601 $ret = '';
602 $helper ??= new TerminalInputHelper($inputStream, false);
603
604 while (!feof($inputStream)) {
605 $helper->waitForInput();
606 $char = fread($inputStream, 1);
607
608 // as opposed to fgets(), fread() returns an empty string when the stream content is empty, not false.
609 if (false === $char || ('' === $ret && '' === $char)) {
610 throw new MissingInputException('Aborted.');
611 }
612
613 if (\PHP_EOL === "{$ret}{$char}" || $exitChar === $char) {
614 break;
615 }
616
617 $ret .= $char;
618
619 if (null === $exitChar && "\n" === $char) {
620 break;
621 }
622 }
623
624 return $ret;
625 }
626 }