4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Console\Helper;
14 use Symfony\Component\Console\Exception\InvalidArgumentException;
15 use Symfony\Component\Console\Exception\RuntimeException;
16 use Symfony\Component\Console\Output\ConsoleOutputInterface;
17 use Symfony\Component\Console\Output\OutputInterface;
18 use Symfony\Component\Console\Formatter\OutputFormatterStyle;
21 * The Dialog class provides helpers to interact with the user.
23 * @author Fabien Potencier <fabien@symfony.com>
25 * @deprecated since version 2.5, to be removed in 3.0.
26 * Use {@link \Symfony\Component\Console\Helper\QuestionHelper} instead.
28 class DialogHelper extends InputAwareHelper
31 private static $shell;
34 public function __construct($triggerDeprecationError = true)
36 if ($triggerDeprecationError) {
37 @trigger_error('"Symfony\Component\Console\Helper\DialogHelper" is deprecated since version 2.5 and will be removed in 3.0. Use "Symfony\Component\Console\Helper\QuestionHelper" instead.', E_USER_DEPRECATED);
42 * Asks the user to select a value.
44 * @param OutputInterface $output An Output instance
45 * @param string|array $question The question to ask
46 * @param array $choices List of choices to pick from
47 * @param bool|string $default The default answer if the user enters nothing
48 * @param bool|int $attempts Max number of times to ask before giving up (false by default, which means infinite)
49 * @param string $errorMessage Message which will be shown if invalid value from choice list would be picked
50 * @param bool $multiselect Select more than one value separated by comma
52 * @return int|string|array The selected value or values (the key of the choices array)
54 * @throws InvalidArgumentException
56 public function select(OutputInterface $output, $question, $choices, $default = null, $attempts = false, $errorMessage = 'Value "%s" is invalid', $multiselect = false)
58 if ($output instanceof ConsoleOutputInterface) {
59 $output = $output->getErrorOutput();
62 $width = max(array_map('strlen', array_keys($choices)));
64 $messages = (array) $question;
65 foreach ($choices as $key => $value) {
66 $messages[] = sprintf(" [<info>%-{$width}s</info>] %s", $key, $value);
69 $output->writeln($messages);
71 $result = $this->askAndValidate($output, '> ', function ($picked) use ($choices, $errorMessage, $multiselect) {
72 // Collapse all spaces.
73 $selectedChoices = str_replace(' ', '', $picked);
76 // Check for a separated comma values
77 if (!preg_match('/^[a-zA-Z0-9_-]+(?:,[a-zA-Z0-9_-]+)*$/', $selectedChoices, $matches)) {
78 throw new InvalidArgumentException(sprintf($errorMessage, $picked));
80 $selectedChoices = explode(',', $selectedChoices);
82 $selectedChoices = array($picked);
85 $multiselectChoices = array();
87 foreach ($selectedChoices as $value) {
88 if (empty($choices[$value])) {
89 throw new InvalidArgumentException(sprintf($errorMessage, $value));
91 $multiselectChoices[] = $value;
95 return $multiselectChoices;
99 }, $attempts, $default);
105 * Asks a question to the user.
107 * @param OutputInterface $output An Output instance
108 * @param string|array $question The question to ask
109 * @param string $default The default answer if none is given by the user
110 * @param array $autocomplete List of values to autocomplete
112 * @return string The user answer
114 * @throws RuntimeException If there is no data to read in the input stream
116 public function ask(OutputInterface $output, $question, $default = null, array $autocomplete = null)
118 if ($this->input && !$this->input->isInteractive()) {
122 if ($output instanceof ConsoleOutputInterface) {
123 $output = $output->getErrorOutput();
126 $output->write($question);
128 $inputStream = $this->inputStream ?: STDIN;
130 if (null === $autocomplete || !$this->hasSttyAvailable()) {
131 $ret = fgets($inputStream, 4096);
132 if (false === $ret) {
133 throw new RuntimeException('Aborted');
141 $matches = $autocomplete;
142 $numMatches = count($matches);
144 $sttyMode = shell_exec('stty -g');
146 // Disable icanon (so we can fread each keypress) and echo (we'll do echoing here instead)
147 shell_exec('stty -icanon -echo');
149 // Add highlighted text style
150 $output->getFormatter()->setStyle('hl', new OutputFormatterStyle('black', 'white'));
153 while (!feof($inputStream)) {
154 $c = fread($inputStream, 1);
156 // Backspace Character
158 if (0 === $numMatches && 0 !== $i) {
160 // Move cursor backwards
161 $output->write("\033[1D");
166 $matches = $autocomplete;
167 $numMatches = count($matches);
172 // Pop the last character off the end of our string
173 $ret = substr($ret, 0, $i);
174 } elseif ("\033" === $c) {
175 // Did we read an escape sequence?
176 $c .= fread($inputStream, 2);
178 // A = Up Arrow. B = Down Arrow
179 if (isset($c[2]) && ('A' === $c[2] || 'B' === $c[2])) {
180 if ('A' === $c[2] && -1 === $ofs) {
184 if (0 === $numMatches) {
188 $ofs += ('A' === $c[2]) ? -1 : 1;
189 $ofs = ($numMatches + $ofs) % $numMatches;
191 } elseif (ord($c) < 32) {
192 if ("\t" === $c || "\n" === $c) {
193 if ($numMatches > 0 && -1 !== $ofs) {
194 $ret = $matches[$ofs];
195 // Echo out remaining chars for current match
196 $output->write(substr($ret, $i));
217 foreach ($autocomplete as $value) {
218 // If typed characters match the beginning chunk of value (e.g. [AcmeDe]moBundle)
219 if (0 === strpos($value, $ret) && $i !== strlen($value)) {
220 $matches[$numMatches++] = $value;
225 // Erase characters from cursor to end of line
226 $output->write("\033[K");
228 if ($numMatches > 0 && -1 !== $ofs) {
229 // Save cursor position
230 $output->write("\0337");
231 // Write highlighted text
232 $output->write('<hl>'.substr($matches[$ofs], $i).'</hl>');
233 // Restore cursor position
234 $output->write("\0338");
238 // Reset stty so it behaves normally again
239 shell_exec(sprintf('stty %s', $sttyMode));
242 return strlen($ret) > 0 ? $ret : $default;
246 * Asks a confirmation to the user.
248 * The question will be asked until the user answers by nothing, yes, or no.
250 * @param OutputInterface $output An Output instance
251 * @param string|array $question The question to ask
252 * @param bool $default The default answer if the user enters nothing
254 * @return bool true if the user has confirmed, false otherwise
256 public function askConfirmation(OutputInterface $output, $question, $default = true)
259 while ($answer && !in_array(strtolower($answer[0]), array('y', 'n'))) {
260 $answer = $this->ask($output, $question);
263 if (false === $default) {
264 return $answer && 'y' == strtolower($answer[0]);
267 return !$answer || 'y' == strtolower($answer[0]);
271 * Asks a question to the user, the response is hidden.
273 * @param OutputInterface $output An Output instance
274 * @param string|array $question The question
275 * @param bool $fallback In case the response can not be hidden, whether to fallback on non-hidden question or not
277 * @return string The answer
279 * @throws RuntimeException In case the fallback is deactivated and the response can not be hidden
281 public function askHiddenResponse(OutputInterface $output, $question, $fallback = true)
283 if ($output instanceof ConsoleOutputInterface) {
284 $output = $output->getErrorOutput();
287 if ('\\' === DIRECTORY_SEPARATOR) {
288 $exe = __DIR__.'/../Resources/bin/hiddeninput.exe';
290 // handle code running from a phar
291 if ('phar:' === substr(__FILE__, 0, 5)) {
292 $tmpExe = sys_get_temp_dir().'/hiddeninput.exe';
297 $output->write($question);
298 $value = rtrim(shell_exec($exe));
299 $output->writeln('');
301 if (isset($tmpExe)) {
308 if ($this->hasSttyAvailable()) {
309 $output->write($question);
311 $sttyMode = shell_exec('stty -g');
313 shell_exec('stty -echo');
314 $value = fgets($this->inputStream ?: STDIN, 4096);
315 shell_exec(sprintf('stty %s', $sttyMode));
317 if (false === $value) {
318 throw new RuntimeException('Aborted');
321 $value = trim($value);
322 $output->writeln('');
327 if (false !== $shell = $this->getShell()) {
328 $output->write($question);
329 $readCmd = $shell === 'csh' ? 'set mypassword = $<' : 'read -r mypassword';
330 $command = sprintf("/usr/bin/env %s -c 'stty -echo; %s; stty echo; echo \$mypassword'", $shell, $readCmd);
331 $value = rtrim(shell_exec($command));
332 $output->writeln('');
338 return $this->ask($output, $question);
341 throw new RuntimeException('Unable to hide the response');
345 * Asks for a value and validates the response.
347 * The validator receives the data to validate. It must return the
348 * validated data when the data is valid and throw an exception
351 * @param OutputInterface $output An Output instance
352 * @param string|array $question The question to ask
353 * @param callable $validator A PHP callback
354 * @param int|false $attempts Max number of times to ask before giving up (false by default, which means infinite)
355 * @param string $default The default answer if none is given by the user
356 * @param array $autocomplete List of values to autocomplete
360 * @throws \Exception When any of the validators return an error
362 public function askAndValidate(OutputInterface $output, $question, $validator, $attempts = false, $default = null, array $autocomplete = null)
366 $interviewer = function () use ($output, $question, $default, $autocomplete, $that) {
367 return $that->ask($output, $question, $default, $autocomplete);
370 return $this->validateAttempts($interviewer, $output, $validator, $attempts);
374 * Asks for a value, hide and validates the response.
376 * The validator receives the data to validate. It must return the
377 * validated data when the data is valid and throw an exception
380 * @param OutputInterface $output An Output instance
381 * @param string|array $question The question to ask
382 * @param callable $validator A PHP callback
383 * @param int|false $attempts Max number of times to ask before giving up (false by default, which means infinite)
384 * @param bool $fallback In case the response can not be hidden, whether to fallback on non-hidden question or not
386 * @return string The response
388 * @throws \Exception When any of the validators return an error
389 * @throws RuntimeException In case the fallback is deactivated and the response can not be hidden
391 public function askHiddenResponseAndValidate(OutputInterface $output, $question, $validator, $attempts = false, $fallback = true)
395 $interviewer = function () use ($output, $question, $fallback, $that) {
396 return $that->askHiddenResponse($output, $question, $fallback);
399 return $this->validateAttempts($interviewer, $output, $validator, $attempts);
403 * Sets the input stream to read from when interacting with the user.
405 * This is mainly useful for testing purpose.
407 * @param resource $stream The input stream
409 public function setInputStream($stream)
411 $this->inputStream = $stream;
415 * Returns the helper's input stream.
417 * @return resource|null The input stream or null if the default STDIN is used
419 public function getInputStream()
421 return $this->inputStream;
427 public function getName()
433 * Return a valid Unix shell.
435 * @return string|bool The valid shell name, false in case no valid shell is found
437 private function getShell()
439 if (null !== self::$shell) {
443 self::$shell = false;
445 if (file_exists('/usr/bin/env')) {
446 // handle other OSs with bash/zsh/ksh/csh if available to hide the answer
447 $test = "/usr/bin/env %s -c 'echo OK' 2> /dev/null";
448 foreach (array('bash', 'zsh', 'ksh', 'csh') as $sh) {
449 if ('OK' === rtrim(shell_exec(sprintf($test, $sh)))) {
459 private function hasSttyAvailable()
461 if (null !== self::$stty) {
465 exec('stty 2>&1', $output, $exitcode);
467 return self::$stty = $exitcode === 0;
471 * Validate an attempt.
473 * @param callable $interviewer A callable that will ask for a question and return the result
474 * @param OutputInterface $output An Output instance
475 * @param callable $validator A PHP callback
476 * @param int|false $attempts Max number of times to ask before giving up; false will ask infinitely
478 * @return string The validated response
480 * @throws \Exception In case the max number of attempts has been reached and no valid response has been given
482 private function validateAttempts($interviewer, OutputInterface $output, $validator, $attempts)
484 if ($output instanceof ConsoleOutputInterface) {
485 $output = $output->getErrorOutput();
489 while (false === $attempts || $attempts--) {
491 $output->writeln($this->getHelperSet()->get('formatter')->formatBlock($e->getMessage(), 'error'));
495 return call_user_func($validator, $interviewer());
496 } catch (\Exception $e) {