DialogHelper.php 16 KB

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