DialogHelper.php 17 KB

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