No Description

DialogHelper.php 16KB

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