d8b373cc1757bb2ae3651c760579326ff0a8bf69
[yaffs-website] / vendor / symfony / console / Helper / QuestionHelper.php
1 <?php
2
3 /*
4  * This file is part of the Symfony package.
5  *
6  * (c) Fabien Potencier <fabien@symfony.com>
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\Exception\InvalidArgumentException;
15 use Symfony\Component\Console\Exception\RuntimeException;
16 use Symfony\Component\Console\Input\InputInterface;
17 use Symfony\Component\Console\Input\StreamableInputInterface;
18 use Symfony\Component\Console\Output\ConsoleOutputInterface;
19 use Symfony\Component\Console\Output\OutputInterface;
20 use Symfony\Component\Console\Formatter\OutputFormatterStyle;
21 use Symfony\Component\Console\Question\Question;
22 use Symfony\Component\Console\Question\ChoiceQuestion;
23
24 /**
25  * The QuestionHelper class provides helpers to interact with the user.
26  *
27  * @author Fabien Potencier <fabien@symfony.com>
28  */
29 class QuestionHelper extends Helper
30 {
31     private $inputStream;
32     private static $shell;
33     private static $stty;
34
35     /**
36      * Asks a question to the user.
37      *
38      * @param InputInterface  $input    An InputInterface instance
39      * @param OutputInterface $output   An OutputInterface instance
40      * @param Question        $question The question to ask
41      *
42      * @return mixed The user answer
43      *
44      * @throws RuntimeException If there is no data to read in the input stream
45      */
46     public function ask(InputInterface $input, OutputInterface $output, Question $question)
47     {
48         if ($output instanceof ConsoleOutputInterface) {
49             $output = $output->getErrorOutput();
50         }
51
52         if (!$input->isInteractive()) {
53             return $question->getDefault();
54         }
55
56         if ($input instanceof StreamableInputInterface && $stream = $input->getStream()) {
57             $this->inputStream = $stream;
58         }
59
60         if (!$question->getValidator()) {
61             return $this->doAsk($output, $question);
62         }
63
64         $interviewer = function () use ($output, $question) {
65             return $this->doAsk($output, $question);
66         };
67
68         return $this->validateAttempts($interviewer, $output, $question);
69     }
70
71     /**
72      * Sets the input stream to read from when interacting with the user.
73      *
74      * This is mainly useful for testing purpose.
75      *
76      * @deprecated since version 3.2, to be removed in 4.0. Use
77      *             StreamableInputInterface::setStream() instead.
78      *
79      * @param resource $stream The input stream
80      *
81      * @throws InvalidArgumentException In case the stream is not a resource
82      */
83     public function setInputStream($stream)
84     {
85         @trigger_error(sprintf('The %s() method is deprecated since version 3.2 and will be removed in 4.0. Use %s::setStream() instead.', __METHOD__, StreamableInputInterface::class), E_USER_DEPRECATED);
86
87         if (!is_resource($stream)) {
88             throw new InvalidArgumentException('Input stream must be a valid resource.');
89         }
90
91         $this->inputStream = $stream;
92     }
93
94     /**
95      * Returns the helper's input stream.
96      *
97      * @deprecated since version 3.2, to be removed in 4.0. Use
98      *             StreamableInputInterface::getStream() instead.
99      *
100      * @return resource
101      */
102     public function getInputStream()
103     {
104         if (0 === func_num_args() || func_get_arg(0)) {
105             @trigger_error(sprintf('The %s() method is deprecated since version 3.2 and will be removed in 4.0. Use %s::getStream() instead.', __METHOD__, StreamableInputInterface::class), E_USER_DEPRECATED);
106         }
107
108         return $this->inputStream;
109     }
110
111     /**
112      * {@inheritdoc}
113      */
114     public function getName()
115     {
116         return 'question';
117     }
118
119     /**
120      * Asks the question to the user.
121      *
122      * @param OutputInterface $output
123      * @param Question        $question
124      *
125      * @return bool|mixed|null|string
126      *
127      * @throws RuntimeException In case the fallback is deactivated and the response cannot be hidden
128      */
129     private function doAsk(OutputInterface $output, Question $question)
130     {
131         $this->writePrompt($output, $question);
132
133         $inputStream = $this->inputStream ?: STDIN;
134         $autocomplete = $question->getAutocompleterValues();
135
136         if (null === $autocomplete || !$this->hasSttyAvailable()) {
137             $ret = false;
138             if ($question->isHidden()) {
139                 try {
140                     $ret = trim($this->getHiddenResponse($output, $inputStream));
141                 } catch (RuntimeException $e) {
142                     if (!$question->isHiddenFallback()) {
143                         throw $e;
144                     }
145                 }
146             }
147
148             if (false === $ret) {
149                 $ret = fgets($inputStream, 4096);
150                 if (false === $ret) {
151                     throw new RuntimeException('Aborted');
152                 }
153                 $ret = trim($ret);
154             }
155         } else {
156             $ret = trim($this->autocomplete($output, $question, $inputStream));
157         }
158
159         $ret = strlen($ret) > 0 ? $ret : $question->getDefault();
160
161         if ($normalizer = $question->getNormalizer()) {
162             return $normalizer($ret);
163         }
164
165         return $ret;
166     }
167
168     /**
169      * Outputs the question prompt.
170      *
171      * @param OutputInterface $output
172      * @param Question        $question
173      */
174     protected function writePrompt(OutputInterface $output, Question $question)
175     {
176         $message = $question->getQuestion();
177
178         if ($question instanceof ChoiceQuestion) {
179             $maxWidth = max(array_map(array($this, 'strlen'), array_keys($question->getChoices())));
180
181             $messages = (array) $question->getQuestion();
182             foreach ($question->getChoices() as $key => $value) {
183                 $width = $maxWidth - $this->strlen($key);
184                 $messages[] = '  [<info>'.$key.str_repeat(' ', $width).'</info>] '.$value;
185             }
186
187             $output->writeln($messages);
188
189             $message = $question->getPrompt();
190         }
191
192         $output->write($message);
193     }
194
195     /**
196      * Outputs an error message.
197      *
198      * @param OutputInterface $output
199      * @param \Exception      $error
200      */
201     protected function writeError(OutputInterface $output, \Exception $error)
202     {
203         if (null !== $this->getHelperSet() && $this->getHelperSet()->has('formatter')) {
204             $message = $this->getHelperSet()->get('formatter')->formatBlock($error->getMessage(), 'error');
205         } else {
206             $message = '<error>'.$error->getMessage().'</error>';
207         }
208
209         $output->writeln($message);
210     }
211
212     /**
213      * Autocompletes a question.
214      *
215      * @param OutputInterface $output
216      * @param Question        $question
217      * @param resource        $inputStream
218      *
219      * @return string
220      */
221     private function autocomplete(OutputInterface $output, Question $question, $inputStream)
222     {
223         $autocomplete = $question->getAutocompleterValues();
224         $ret = '';
225
226         $i = 0;
227         $ofs = -1;
228         $matches = $autocomplete;
229         $numMatches = count($matches);
230
231         $sttyMode = shell_exec('stty -g');
232
233         // Disable icanon (so we can fread each keypress) and echo (we'll do echoing here instead)
234         shell_exec('stty -icanon -echo');
235
236         // Add highlighted text style
237         $output->getFormatter()->setStyle('hl', new OutputFormatterStyle('black', 'white'));
238
239         // Read a keypress
240         while (!feof($inputStream)) {
241             $c = fread($inputStream, 1);
242
243             // Backspace Character
244             if ("\177" === $c) {
245                 if (0 === $numMatches && 0 !== $i) {
246                     --$i;
247                     // Move cursor backwards
248                     $output->write("\033[1D");
249                 }
250
251                 if ($i === 0) {
252                     $ofs = -1;
253                     $matches = $autocomplete;
254                     $numMatches = count($matches);
255                 } else {
256                     $numMatches = 0;
257                 }
258
259                 // Pop the last character off the end of our string
260                 $ret = substr($ret, 0, $i);
261             } elseif ("\033" === $c) {
262                 // Did we read an escape sequence?
263                 $c .= fread($inputStream, 2);
264
265                 // A = Up Arrow. B = Down Arrow
266                 if (isset($c[2]) && ('A' === $c[2] || 'B' === $c[2])) {
267                     if ('A' === $c[2] && -1 === $ofs) {
268                         $ofs = 0;
269                     }
270
271                     if (0 === $numMatches) {
272                         continue;
273                     }
274
275                     $ofs += ('A' === $c[2]) ? -1 : 1;
276                     $ofs = ($numMatches + $ofs) % $numMatches;
277                 }
278             } elseif (ord($c) < 32) {
279                 if ("\t" === $c || "\n" === $c) {
280                     if ($numMatches > 0 && -1 !== $ofs) {
281                         $ret = $matches[$ofs];
282                         // Echo out remaining chars for current match
283                         $output->write(substr($ret, $i));
284                         $i = strlen($ret);
285                     }
286
287                     if ("\n" === $c) {
288                         $output->write($c);
289                         break;
290                     }
291
292                     $numMatches = 0;
293                 }
294
295                 continue;
296             } else {
297                 $output->write($c);
298                 $ret .= $c;
299                 ++$i;
300
301                 $numMatches = 0;
302                 $ofs = 0;
303
304                 foreach ($autocomplete as $value) {
305                     // If typed characters match the beginning chunk of value (e.g. [AcmeDe]moBundle)
306                     if (0 === strpos($value, $ret) && $i !== strlen($value)) {
307                         $matches[$numMatches++] = $value;
308                     }
309                 }
310             }
311
312             // Erase characters from cursor to end of line
313             $output->write("\033[K");
314
315             if ($numMatches > 0 && -1 !== $ofs) {
316                 // Save cursor position
317                 $output->write("\0337");
318                 // Write highlighted text
319                 $output->write('<hl>'.substr($matches[$ofs], $i).'</hl>');
320                 // Restore cursor position
321                 $output->write("\0338");
322             }
323         }
324
325         // Reset stty so it behaves normally again
326         shell_exec(sprintf('stty %s', $sttyMode));
327
328         return $ret;
329     }
330
331     /**
332      * Gets a hidden response from user.
333      *
334      * @param OutputInterface $output      An Output instance
335      * @param resource        $inputStream The handler resource
336      *
337      * @return string The answer
338      *
339      * @throws RuntimeException In case the fallback is deactivated and the response cannot be hidden
340      */
341     private function getHiddenResponse(OutputInterface $output, $inputStream)
342     {
343         if ('\\' === DIRECTORY_SEPARATOR) {
344             $exe = __DIR__.'/../Resources/bin/hiddeninput.exe';
345
346             // handle code running from a phar
347             if ('phar:' === substr(__FILE__, 0, 5)) {
348                 $tmpExe = sys_get_temp_dir().'/hiddeninput.exe';
349                 copy($exe, $tmpExe);
350                 $exe = $tmpExe;
351             }
352
353             $value = rtrim(shell_exec($exe));
354             $output->writeln('');
355
356             if (isset($tmpExe)) {
357                 unlink($tmpExe);
358             }
359
360             return $value;
361         }
362
363         if ($this->hasSttyAvailable()) {
364             $sttyMode = shell_exec('stty -g');
365
366             shell_exec('stty -echo');
367             $value = fgets($inputStream, 4096);
368             shell_exec(sprintf('stty %s', $sttyMode));
369
370             if (false === $value) {
371                 throw new RuntimeException('Aborted');
372             }
373
374             $value = trim($value);
375             $output->writeln('');
376
377             return $value;
378         }
379
380         if (false !== $shell = $this->getShell()) {
381             $readCmd = $shell === 'csh' ? 'set mypassword = $<' : 'read -r mypassword';
382             $command = sprintf("/usr/bin/env %s -c 'stty -echo; %s; stty echo; echo \$mypassword'", $shell, $readCmd);
383             $value = rtrim(shell_exec($command));
384             $output->writeln('');
385
386             return $value;
387         }
388
389         throw new RuntimeException('Unable to hide the response.');
390     }
391
392     /**
393      * Validates an attempt.
394      *
395      * @param callable        $interviewer A callable that will ask for a question and return the result
396      * @param OutputInterface $output      An Output instance
397      * @param Question        $question    A Question instance
398      *
399      * @return mixed The validated response
400      *
401      * @throws \Exception In case the max number of attempts has been reached and no valid response has been given
402      */
403     private function validateAttempts(callable $interviewer, OutputInterface $output, Question $question)
404     {
405         $error = null;
406         $attempts = $question->getMaxAttempts();
407         while (null === $attempts || $attempts--) {
408             if (null !== $error) {
409                 $this->writeError($output, $error);
410             }
411
412             try {
413                 return call_user_func($question->getValidator(), $interviewer());
414             } catch (RuntimeException $e) {
415                 throw $e;
416             } catch (\Exception $error) {
417             }
418         }
419
420         throw $error;
421     }
422
423     /**
424      * Returns a valid unix shell.
425      *
426      * @return string|bool The valid shell name, false in case no valid shell is found
427      */
428     private function getShell()
429     {
430         if (null !== self::$shell) {
431             return self::$shell;
432         }
433
434         self::$shell = false;
435
436         if (file_exists('/usr/bin/env')) {
437             // handle other OSs with bash/zsh/ksh/csh if available to hide the answer
438             $test = "/usr/bin/env %s -c 'echo OK' 2> /dev/null";
439             foreach (array('bash', 'zsh', 'ksh', 'csh') as $sh) {
440                 if ('OK' === rtrim(shell_exec(sprintf($test, $sh)))) {
441                     self::$shell = $sh;
442                     break;
443                 }
444             }
445         }
446
447         return self::$shell;
448     }
449
450     /**
451      * Returns whether Stty is available or not.
452      *
453      * @return bool
454      */
455     private function hasSttyAvailable()
456     {
457         if (null !== self::$stty) {
458             return self::$stty;
459         }
460
461         exec('stty 2>&1', $output, $exitcode);
462
463         return self::$stty = $exitcode === 0;
464     }
465 }