DialogHelper.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Console\Helper;
  11. use Symfony\Component\Console\Exception\InvalidArgumentException;
  12. use Symfony\Component\Console\Exception\RuntimeException;
  13. use Symfony\Component\Console\Output\ConsoleOutputInterface;
  14. use Symfony\Component\Console\Output\OutputInterface;
  15. use Symfony\Component\Console\Formatter\OutputFormatterStyle;
  16. /**
  17. * The Dialog class provides helpers to interact with the user.
  18. *
  19. * @author Fabien Potencier <fabien@symfony.com>
  20. *
  21. * @deprecated since version 2.5, to be removed in 3.0.
  22. * Use {@link \Symfony\Component\Console\Helper\QuestionHelper} instead.
  23. */
  24. class DialogHelper extends InputAwareHelper
  25. {
  26. private $inputStream;
  27. private static $shell;
  28. private static $stty;
  29. public function __construct($triggerDeprecationError = true)
  30. {
  31. if ($triggerDeprecationError) {
  32. @trigger_error('"Symfony\Component\Console\Helper\DialogHelper" is deprecated since Symfony 2.5 and will be removed in 3.0. Use "Symfony\Component\Console\Helper\QuestionHelper" instead.', E_USER_DEPRECATED);
  33. }
  34. }
  35. /**
  36. * Asks the user to select a value.
  37. *
  38. * @param OutputInterface $output An Output instance
  39. * @param string|array $question The question to ask
  40. * @param array $choices List of choices to pick from
  41. * @param bool|string $default The default answer if the user enters nothing
  42. * @param bool|int $attempts Max number of times to ask before giving up (false by default, which means infinite)
  43. * @param string $errorMessage Message which will be shown if invalid value from choice list would be picked
  44. * @param bool $multiselect Select more than one value separated by comma
  45. *
  46. * @return int|string|array The selected value or values (the key of the choices array)
  47. *
  48. * @throws InvalidArgumentException
  49. */
  50. public function select(OutputInterface $output, $question, $choices, $default = null, $attempts = false, $errorMessage = 'Value "%s" is invalid', $multiselect = false)
  51. {
  52. if ($output instanceof ConsoleOutputInterface) {
  53. $output = $output->getErrorOutput();
  54. }
  55. $width = max(array_map('strlen', array_keys($choices)));
  56. $messages = (array) $question;
  57. foreach ($choices as $key => $value) {
  58. $messages[] = sprintf(" [<info>%-{$width}s</info>] %s", $key, $value);
  59. }
  60. $output->writeln($messages);
  61. $result = $this->askAndValidate($output, '> ', function ($picked) use ($choices, $errorMessage, $multiselect) {
  62. // Collapse all spaces.
  63. $selectedChoices = str_replace(' ', '', $picked);
  64. if ($multiselect) {
  65. // Check for a separated comma values
  66. if (!preg_match('/^[a-zA-Z0-9_-]+(?:,[a-zA-Z0-9_-]+)*$/', $selectedChoices, $matches)) {
  67. throw new InvalidArgumentException(sprintf($errorMessage, $picked));
  68. }
  69. $selectedChoices = explode(',', $selectedChoices);
  70. } else {
  71. $selectedChoices = array($picked);
  72. }
  73. $multiselectChoices = array();
  74. foreach ($selectedChoices as $value) {
  75. if (empty($choices[$value])) {
  76. throw new InvalidArgumentException(sprintf($errorMessage, $value));
  77. }
  78. $multiselectChoices[] = $value;
  79. }
  80. if ($multiselect) {
  81. return $multiselectChoices;
  82. }
  83. return $picked;
  84. }, $attempts, $default);
  85. return $result;
  86. }
  87. /**
  88. * Asks a question to the user.
  89. *
  90. * @param OutputInterface $output An Output instance
  91. * @param string|array $question The question to ask
  92. * @param string $default The default answer if none is given by the user
  93. * @param array $autocomplete List of values to autocomplete
  94. *
  95. * @return string The user answer
  96. *
  97. * @throws RuntimeException If there is no data to read in the input stream
  98. */
  99. public function ask(OutputInterface $output, $question, $default = null, array $autocomplete = null)
  100. {
  101. if ($this->input && !$this->input->isInteractive()) {
  102. return $default;
  103. }
  104. if ($output instanceof ConsoleOutputInterface) {
  105. $output = $output->getErrorOutput();
  106. }
  107. $output->write($question);
  108. $inputStream = $this->inputStream ?: STDIN;
  109. if (null === $autocomplete || !$this->hasSttyAvailable()) {
  110. $ret = fgets($inputStream, 4096);
  111. if (false === $ret) {
  112. throw new RuntimeException('Aborted');
  113. }
  114. $ret = trim($ret);
  115. } else {
  116. $ret = '';
  117. $i = 0;
  118. $ofs = -1;
  119. $matches = $autocomplete;
  120. $numMatches = count($matches);
  121. $sttyMode = shell_exec('stty -g');
  122. // Disable icanon (so we can fread each keypress) and echo (we'll do echoing here instead)
  123. shell_exec('stty -icanon -echo');
  124. // Add highlighted text style
  125. $output->getFormatter()->setStyle('hl', new OutputFormatterStyle('black', 'white'));
  126. // Read a keypress
  127. while (!feof($inputStream)) {
  128. $c = fread($inputStream, 1);
  129. // Backspace Character
  130. if ("\177" === $c) {
  131. if (0 === $numMatches && 0 !== $i) {
  132. --$i;
  133. // Move cursor backwards
  134. $output->write("\033[1D");
  135. }
  136. if (0 === $i) {
  137. $ofs = -1;
  138. $matches = $autocomplete;
  139. $numMatches = count($matches);
  140. } else {
  141. $numMatches = 0;
  142. }
  143. // Pop the last character off the end of our string
  144. $ret = substr($ret, 0, $i);
  145. } elseif ("\033" === $c) {
  146. // Did we read an escape sequence?
  147. $c .= fread($inputStream, 2);
  148. // A = Up Arrow. B = Down Arrow
  149. if (isset($c[2]) && ('A' === $c[2] || 'B' === $c[2])) {
  150. if ('A' === $c[2] && -1 === $ofs) {
  151. $ofs = 0;
  152. }
  153. if (0 === $numMatches) {
  154. continue;
  155. }
  156. $ofs += ('A' === $c[2]) ? -1 : 1;
  157. $ofs = ($numMatches + $ofs) % $numMatches;
  158. }
  159. } elseif (ord($c) < 32) {
  160. if ("\t" === $c || "\n" === $c) {
  161. if ($numMatches > 0 && -1 !== $ofs) {
  162. $ret = $matches[$ofs];
  163. // Echo out remaining chars for current match
  164. $output->write(substr($ret, $i));
  165. $i = strlen($ret);
  166. }
  167. if ("\n" === $c) {
  168. $output->write($c);
  169. break;
  170. }
  171. $numMatches = 0;
  172. }
  173. continue;
  174. } else {
  175. $output->write($c);
  176. $ret .= $c;
  177. ++$i;
  178. $numMatches = 0;
  179. $ofs = 0;
  180. foreach ($autocomplete as $value) {
  181. // If typed characters match the beginning chunk of value (e.g. [AcmeDe]moBundle)
  182. if (0 === strpos($value, $ret) && $i !== strlen($value)) {
  183. $matches[$numMatches++] = $value;
  184. }
  185. }
  186. }
  187. // Erase characters from cursor to end of line
  188. $output->write("\033[K");
  189. if ($numMatches > 0 && -1 !== $ofs) {
  190. // Save cursor position
  191. $output->write("\0337");
  192. // Write highlighted text
  193. $output->write('<hl>'.substr($matches[$ofs], $i).'</hl>');
  194. // Restore cursor position
  195. $output->write("\0338");
  196. }
  197. }
  198. // Reset stty so it behaves normally again
  199. shell_exec(sprintf('stty %s', $sttyMode));
  200. }
  201. return strlen($ret) > 0 ? $ret : $default;
  202. }
  203. /**
  204. * Asks a confirmation to the user.
  205. *
  206. * The question will be asked until the user answers by nothing, yes, or no.
  207. *
  208. * @param OutputInterface $output An Output instance
  209. * @param string|array $question The question to ask
  210. * @param bool $default The default answer if the user enters nothing
  211. *
  212. * @return bool true if the user has confirmed, false otherwise
  213. */
  214. public function askConfirmation(OutputInterface $output, $question, $default = true)
  215. {
  216. $answer = 'z';
  217. while ($answer && !in_array(strtolower($answer[0]), array('y', 'n'))) {
  218. $answer = $this->ask($output, $question);
  219. }
  220. if (false === $default) {
  221. return $answer && 'y' == strtolower($answer[0]);
  222. }
  223. return !$answer || 'y' == strtolower($answer[0]);
  224. }
  225. /**
  226. * Asks a question to the user, the response is hidden.
  227. *
  228. * @param OutputInterface $output An Output instance
  229. * @param string|array $question The question
  230. * @param bool $fallback In case the response can not be hidden, whether to fallback on non-hidden question or not
  231. *
  232. * @return string The answer
  233. *
  234. * @throws RuntimeException In case the fallback is deactivated and the response can not be hidden
  235. */
  236. public function askHiddenResponse(OutputInterface $output, $question, $fallback = true)
  237. {
  238. if ($output instanceof ConsoleOutputInterface) {
  239. $output = $output->getErrorOutput();
  240. }
  241. if ('\\' === DIRECTORY_SEPARATOR) {
  242. $exe = __DIR__.'/../Resources/bin/hiddeninput.exe';
  243. // handle code running from a phar
  244. if ('phar:' === substr(__FILE__, 0, 5)) {
  245. $tmpExe = sys_get_temp_dir().'/hiddeninput.exe';
  246. copy($exe, $tmpExe);
  247. $exe = $tmpExe;
  248. }
  249. $output->write($question);
  250. $value = rtrim(shell_exec($exe));
  251. $output->writeln('');
  252. if (isset($tmpExe)) {
  253. unlink($tmpExe);
  254. }
  255. return $value;
  256. }
  257. if ($this->hasSttyAvailable()) {
  258. $output->write($question);
  259. $sttyMode = shell_exec('stty -g');
  260. shell_exec('stty -echo');
  261. $value = fgets($this->inputStream ?: STDIN, 4096);
  262. shell_exec(sprintf('stty %s', $sttyMode));
  263. if (false === $value) {
  264. throw new RuntimeException('Aborted');
  265. }
  266. $value = trim($value);
  267. $output->writeln('');
  268. return $value;
  269. }
  270. if (false !== $shell = $this->getShell()) {
  271. $output->write($question);
  272. $readCmd = 'csh' === $shell ? 'set mypassword = $<' : 'read -r mypassword';
  273. $command = sprintf("/usr/bin/env %s -c 'stty -echo; %s; stty echo; echo \$mypassword'", $shell, $readCmd);
  274. $value = rtrim(shell_exec($command));
  275. $output->writeln('');
  276. return $value;
  277. }
  278. if ($fallback) {
  279. return $this->ask($output, $question);
  280. }
  281. throw new RuntimeException('Unable to hide the response');
  282. }
  283. /**
  284. * Asks for a value and validates the response.
  285. *
  286. * The validator receives the data to validate. It must return the
  287. * validated data when the data is valid and throw an exception
  288. * otherwise.
  289. *
  290. * @param OutputInterface $output An Output instance
  291. * @param string|array $question The question to ask
  292. * @param callable $validator A PHP callback
  293. * @param int|false $attempts Max number of times to ask before giving up (false by default, which means infinite)
  294. * @param string $default The default answer if none is given by the user
  295. * @param array $autocomplete List of values to autocomplete
  296. *
  297. * @return mixed
  298. *
  299. * @throws \Exception When any of the validators return an error
  300. */
  301. public function askAndValidate(OutputInterface $output, $question, $validator, $attempts = false, $default = null, array $autocomplete = null)
  302. {
  303. $that = $this;
  304. $interviewer = function () use ($output, $question, $default, $autocomplete, $that) {
  305. return $that->ask($output, $question, $default, $autocomplete);
  306. };
  307. return $this->validateAttempts($interviewer, $output, $validator, $attempts);
  308. }
  309. /**
  310. * Asks for a value, hide and validates the response.
  311. *
  312. * The validator receives the data to validate. It must return the
  313. * validated data when the data is valid and throw an exception
  314. * otherwise.
  315. *
  316. * @param OutputInterface $output An Output instance
  317. * @param string|array $question The question to ask
  318. * @param callable $validator A PHP callback
  319. * @param int|false $attempts Max number of times to ask before giving up (false by default, which means infinite)
  320. * @param bool $fallback In case the response can not be hidden, whether to fallback on non-hidden question or not
  321. *
  322. * @return string The response
  323. *
  324. * @throws \Exception When any of the validators return an error
  325. * @throws RuntimeException In case the fallback is deactivated and the response can not be hidden
  326. */
  327. public function askHiddenResponseAndValidate(OutputInterface $output, $question, $validator, $attempts = false, $fallback = true)
  328. {
  329. $that = $this;
  330. $interviewer = function () use ($output, $question, $fallback, $that) {
  331. return $that->askHiddenResponse($output, $question, $fallback);
  332. };
  333. return $this->validateAttempts($interviewer, $output, $validator, $attempts);
  334. }
  335. /**
  336. * Sets the input stream to read from when interacting with the user.
  337. *
  338. * This is mainly useful for testing purpose.
  339. *
  340. * @param resource $stream The input stream
  341. */
  342. public function setInputStream($stream)
  343. {
  344. $this->inputStream = $stream;
  345. }
  346. /**
  347. * Returns the helper's input stream.
  348. *
  349. * @return resource|null The input stream or null if the default STDIN is used
  350. */
  351. public function getInputStream()
  352. {
  353. return $this->inputStream;
  354. }
  355. /**
  356. * {@inheritdoc}
  357. */
  358. public function getName()
  359. {
  360. return 'dialog';
  361. }
  362. /**
  363. * Return a valid Unix shell.
  364. *
  365. * @return string|bool The valid shell name, false in case no valid shell is found
  366. */
  367. private function getShell()
  368. {
  369. if (null !== self::$shell) {
  370. return self::$shell;
  371. }
  372. self::$shell = false;
  373. if (file_exists('/usr/bin/env')) {
  374. // handle other OSs with bash/zsh/ksh/csh if available to hide the answer
  375. $test = "/usr/bin/env %s -c 'echo OK' 2> /dev/null";
  376. foreach (array('bash', 'zsh', 'ksh', 'csh') as $sh) {
  377. if ('OK' === rtrim(shell_exec(sprintf($test, $sh)))) {
  378. self::$shell = $sh;
  379. break;
  380. }
  381. }
  382. }
  383. return self::$shell;
  384. }
  385. private function hasSttyAvailable()
  386. {
  387. if (null !== self::$stty) {
  388. return self::$stty;
  389. }
  390. exec('stty 2>&1', $output, $exitcode);
  391. return self::$stty = 0 === $exitcode;
  392. }
  393. /**
  394. * Validate 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 callable $validator A PHP callback
  399. * @param int|false $attempts Max number of times to ask before giving up; false will ask infinitely
  400. *
  401. * @return string The validated response
  402. *
  403. * @throws \Exception In case the max number of attempts has been reached and no valid response has been given
  404. */
  405. private function validateAttempts($interviewer, OutputInterface $output, $validator, $attempts)
  406. {
  407. if ($output instanceof ConsoleOutputInterface) {
  408. $output = $output->getErrorOutput();
  409. }
  410. $e = null;
  411. while (false === $attempts || $attempts--) {
  412. if (null !== $e) {
  413. $output->writeln($this->getHelperSet()->get('formatter')->formatBlock($e->getMessage(), 'error'));
  414. }
  415. try {
  416. return call_user_func($validator, $interviewer());
  417. } catch (\Exception $e) {
  418. }
  419. }
  420. throw $e;
  421. }
  422. }