Mercurial > hg > isophonics-drupal-site
comparison vendor/symfony/console/Helper/QuestionHelper.php @ 0:4c8ae668cc8c
Initial import (non-working)
author | Chris Cannam |
---|---|
date | Wed, 29 Nov 2017 16:09:58 +0000 |
parents | |
children | 7a779792577d |
comparison
equal
deleted
inserted
replaced
-1:000000000000 | 0:4c8ae668cc8c |
---|---|
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 \Exception | |
128 * @throws \RuntimeException | |
129 */ | |
130 private function doAsk(OutputInterface $output, Question $question) | |
131 { | |
132 $this->writePrompt($output, $question); | |
133 | |
134 $inputStream = $this->inputStream ?: STDIN; | |
135 $autocomplete = $question->getAutocompleterValues(); | |
136 | |
137 if (null === $autocomplete || !$this->hasSttyAvailable()) { | |
138 $ret = false; | |
139 if ($question->isHidden()) { | |
140 try { | |
141 $ret = trim($this->getHiddenResponse($output, $inputStream)); | |
142 } catch (\RuntimeException $e) { | |
143 if (!$question->isHiddenFallback()) { | |
144 throw $e; | |
145 } | |
146 } | |
147 } | |
148 | |
149 if (false === $ret) { | |
150 $ret = fgets($inputStream, 4096); | |
151 if (false === $ret) { | |
152 throw new RuntimeException('Aborted'); | |
153 } | |
154 $ret = trim($ret); | |
155 } | |
156 } else { | |
157 $ret = trim($this->autocomplete($output, $question, $inputStream)); | |
158 } | |
159 | |
160 $ret = strlen($ret) > 0 ? $ret : $question->getDefault(); | |
161 | |
162 if ($normalizer = $question->getNormalizer()) { | |
163 return $normalizer($ret); | |
164 } | |
165 | |
166 return $ret; | |
167 } | |
168 | |
169 /** | |
170 * Outputs the question prompt. | |
171 * | |
172 * @param OutputInterface $output | |
173 * @param Question $question | |
174 */ | |
175 protected function writePrompt(OutputInterface $output, Question $question) | |
176 { | |
177 $message = $question->getQuestion(); | |
178 | |
179 if ($question instanceof ChoiceQuestion) { | |
180 $maxWidth = max(array_map(array($this, 'strlen'), array_keys($question->getChoices()))); | |
181 | |
182 $messages = (array) $question->getQuestion(); | |
183 foreach ($question->getChoices() as $key => $value) { | |
184 $width = $maxWidth - $this->strlen($key); | |
185 $messages[] = ' [<info>'.$key.str_repeat(' ', $width).'</info>] '.$value; | |
186 } | |
187 | |
188 $output->writeln($messages); | |
189 | |
190 $message = $question->getPrompt(); | |
191 } | |
192 | |
193 $output->write($message); | |
194 } | |
195 | |
196 /** | |
197 * Outputs an error message. | |
198 * | |
199 * @param OutputInterface $output | |
200 * @param \Exception $error | |
201 */ | |
202 protected function writeError(OutputInterface $output, \Exception $error) | |
203 { | |
204 if (null !== $this->getHelperSet() && $this->getHelperSet()->has('formatter')) { | |
205 $message = $this->getHelperSet()->get('formatter')->formatBlock($error->getMessage(), 'error'); | |
206 } else { | |
207 $message = '<error>'.$error->getMessage().'</error>'; | |
208 } | |
209 | |
210 $output->writeln($message); | |
211 } | |
212 | |
213 /** | |
214 * Autocompletes a question. | |
215 * | |
216 * @param OutputInterface $output | |
217 * @param Question $question | |
218 * @param resource $inputStream | |
219 * | |
220 * @return string | |
221 */ | |
222 private function autocomplete(OutputInterface $output, Question $question, $inputStream) | |
223 { | |
224 $autocomplete = $question->getAutocompleterValues(); | |
225 $ret = ''; | |
226 | |
227 $i = 0; | |
228 $ofs = -1; | |
229 $matches = $autocomplete; | |
230 $numMatches = count($matches); | |
231 | |
232 $sttyMode = shell_exec('stty -g'); | |
233 | |
234 // Disable icanon (so we can fread each keypress) and echo (we'll do echoing here instead) | |
235 shell_exec('stty -icanon -echo'); | |
236 | |
237 // Add highlighted text style | |
238 $output->getFormatter()->setStyle('hl', new OutputFormatterStyle('black', 'white')); | |
239 | |
240 // Read a keypress | |
241 while (!feof($inputStream)) { | |
242 $c = fread($inputStream, 1); | |
243 | |
244 // Backspace Character | |
245 if ("\177" === $c) { | |
246 if (0 === $numMatches && 0 !== $i) { | |
247 --$i; | |
248 // Move cursor backwards | |
249 $output->write("\033[1D"); | |
250 } | |
251 | |
252 if ($i === 0) { | |
253 $ofs = -1; | |
254 $matches = $autocomplete; | |
255 $numMatches = count($matches); | |
256 } else { | |
257 $numMatches = 0; | |
258 } | |
259 | |
260 // Pop the last character off the end of our string | |
261 $ret = substr($ret, 0, $i); | |
262 } elseif ("\033" === $c) { | |
263 // Did we read an escape sequence? | |
264 $c .= fread($inputStream, 2); | |
265 | |
266 // A = Up Arrow. B = Down Arrow | |
267 if (isset($c[2]) && ('A' === $c[2] || 'B' === $c[2])) { | |
268 if ('A' === $c[2] && -1 === $ofs) { | |
269 $ofs = 0; | |
270 } | |
271 | |
272 if (0 === $numMatches) { | |
273 continue; | |
274 } | |
275 | |
276 $ofs += ('A' === $c[2]) ? -1 : 1; | |
277 $ofs = ($numMatches + $ofs) % $numMatches; | |
278 } | |
279 } elseif (ord($c) < 32) { | |
280 if ("\t" === $c || "\n" === $c) { | |
281 if ($numMatches > 0 && -1 !== $ofs) { | |
282 $ret = $matches[$ofs]; | |
283 // Echo out remaining chars for current match | |
284 $output->write(substr($ret, $i)); | |
285 $i = strlen($ret); | |
286 } | |
287 | |
288 if ("\n" === $c) { | |
289 $output->write($c); | |
290 break; | |
291 } | |
292 | |
293 $numMatches = 0; | |
294 } | |
295 | |
296 continue; | |
297 } else { | |
298 $output->write($c); | |
299 $ret .= $c; | |
300 ++$i; | |
301 | |
302 $numMatches = 0; | |
303 $ofs = 0; | |
304 | |
305 foreach ($autocomplete as $value) { | |
306 // If typed characters match the beginning chunk of value (e.g. [AcmeDe]moBundle) | |
307 if (0 === strpos($value, $ret) && $i !== strlen($value)) { | |
308 $matches[$numMatches++] = $value; | |
309 } | |
310 } | |
311 } | |
312 | |
313 // Erase characters from cursor to end of line | |
314 $output->write("\033[K"); | |
315 | |
316 if ($numMatches > 0 && -1 !== $ofs) { | |
317 // Save cursor position | |
318 $output->write("\0337"); | |
319 // Write highlighted text | |
320 $output->write('<hl>'.substr($matches[$ofs], $i).'</hl>'); | |
321 // Restore cursor position | |
322 $output->write("\0338"); | |
323 } | |
324 } | |
325 | |
326 // Reset stty so it behaves normally again | |
327 shell_exec(sprintf('stty %s', $sttyMode)); | |
328 | |
329 return $ret; | |
330 } | |
331 | |
332 /** | |
333 * Gets a hidden response from user. | |
334 * | |
335 * @param OutputInterface $output An Output instance | |
336 * @param resource $inputStream The handler resource | |
337 * | |
338 * @return string The answer | |
339 * | |
340 * @throws RuntimeException In case the fallback is deactivated and the response cannot be hidden | |
341 */ | |
342 private function getHiddenResponse(OutputInterface $output, $inputStream) | |
343 { | |
344 if ('\\' === DIRECTORY_SEPARATOR) { | |
345 $exe = __DIR__.'/../Resources/bin/hiddeninput.exe'; | |
346 | |
347 // handle code running from a phar | |
348 if ('phar:' === substr(__FILE__, 0, 5)) { | |
349 $tmpExe = sys_get_temp_dir().'/hiddeninput.exe'; | |
350 copy($exe, $tmpExe); | |
351 $exe = $tmpExe; | |
352 } | |
353 | |
354 $value = rtrim(shell_exec($exe)); | |
355 $output->writeln(''); | |
356 | |
357 if (isset($tmpExe)) { | |
358 unlink($tmpExe); | |
359 } | |
360 | |
361 return $value; | |
362 } | |
363 | |
364 if ($this->hasSttyAvailable()) { | |
365 $sttyMode = shell_exec('stty -g'); | |
366 | |
367 shell_exec('stty -echo'); | |
368 $value = fgets($inputStream, 4096); | |
369 shell_exec(sprintf('stty %s', $sttyMode)); | |
370 | |
371 if (false === $value) { | |
372 throw new RuntimeException('Aborted'); | |
373 } | |
374 | |
375 $value = trim($value); | |
376 $output->writeln(''); | |
377 | |
378 return $value; | |
379 } | |
380 | |
381 if (false !== $shell = $this->getShell()) { | |
382 $readCmd = $shell === 'csh' ? 'set mypassword = $<' : 'read -r mypassword'; | |
383 $command = sprintf("/usr/bin/env %s -c 'stty -echo; %s; stty echo; echo \$mypassword'", $shell, $readCmd); | |
384 $value = rtrim(shell_exec($command)); | |
385 $output->writeln(''); | |
386 | |
387 return $value; | |
388 } | |
389 | |
390 throw new RuntimeException('Unable to hide the response.'); | |
391 } | |
392 | |
393 /** | |
394 * Validates an attempt. | |
395 * | |
396 * @param callable $interviewer A callable that will ask for a question and return the result | |
397 * @param OutputInterface $output An Output instance | |
398 * @param Question $question A Question instance | |
399 * | |
400 * @return mixed The validated response | |
401 * | |
402 * @throws \Exception In case the max number of attempts has been reached and no valid response has been given | |
403 */ | |
404 private function validateAttempts(callable $interviewer, OutputInterface $output, Question $question) | |
405 { | |
406 $error = null; | |
407 $attempts = $question->getMaxAttempts(); | |
408 while (null === $attempts || $attempts--) { | |
409 if (null !== $error) { | |
410 $this->writeError($output, $error); | |
411 } | |
412 | |
413 try { | |
414 return call_user_func($question->getValidator(), $interviewer()); | |
415 } catch (RuntimeException $e) { | |
416 throw $e; | |
417 } catch (\Exception $error) { | |
418 } | |
419 } | |
420 | |
421 throw $error; | |
422 } | |
423 | |
424 /** | |
425 * Returns a valid unix shell. | |
426 * | |
427 * @return string|bool The valid shell name, false in case no valid shell is found | |
428 */ | |
429 private function getShell() | |
430 { | |
431 if (null !== self::$shell) { | |
432 return self::$shell; | |
433 } | |
434 | |
435 self::$shell = false; | |
436 | |
437 if (file_exists('/usr/bin/env')) { | |
438 // handle other OSs with bash/zsh/ksh/csh if available to hide the answer | |
439 $test = "/usr/bin/env %s -c 'echo OK' 2> /dev/null"; | |
440 foreach (array('bash', 'zsh', 'ksh', 'csh') as $sh) { | |
441 if ('OK' === rtrim(shell_exec(sprintf($test, $sh)))) { | |
442 self::$shell = $sh; | |
443 break; | |
444 } | |
445 } | |
446 } | |
447 | |
448 return self::$shell; | |
449 } | |
450 | |
451 /** | |
452 * Returns whether Stty is available or not. | |
453 * | |
454 * @return bool | |
455 */ | |
456 private function hasSttyAvailable() | |
457 { | |
458 if (null !== self::$stty) { | |
459 return self::$stty; | |
460 } | |
461 | |
462 exec('stty 2>&1', $output, $exitcode); | |
463 | |
464 return self::$stty = $exitcode === 0; | |
465 } | |
466 } |