Ask.php 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: yunwuxin <448901948@qq.com>
  10. // +----------------------------------------------------------------------
  11. namespace think\console\output;
  12. use think\console\Input;
  13. use think\console\Output;
  14. use think\console\output\question\Choice;
  15. use think\console\output\question\Confirmation;
  16. class Ask
  17. {
  18. private static $stty;
  19. private static $shell;
  20. /** @var Input */
  21. protected $input;
  22. /** @var Output */
  23. protected $output;
  24. /** @var Question */
  25. protected $question;
  26. public function __construct(Input $input, Output $output, Question $question)
  27. {
  28. $this->input = $input;
  29. $this->output = $output;
  30. $this->question = $question;
  31. }
  32. public function run()
  33. {
  34. if (!$this->input->isInteractive()) {
  35. return $this->question->getDefault();
  36. }
  37. if (!$this->question->getValidator()) {
  38. return $this->doAsk();
  39. }
  40. $that = $this;
  41. $interviewer = function () use ($that) {
  42. return $that->doAsk();
  43. };
  44. return $this->validateAttempts($interviewer);
  45. }
  46. protected function doAsk()
  47. {
  48. $this->writePrompt();
  49. $inputStream = STDIN;
  50. $autocomplete = $this->question->getAutocompleterValues();
  51. if (null === $autocomplete || !$this->hasSttyAvailable()) {
  52. $ret = false;
  53. if ($this->question->isHidden()) {
  54. try {
  55. $ret = trim($this->getHiddenResponse($inputStream));
  56. } catch (\RuntimeException $e) {
  57. if (!$this->question->isHiddenFallback()) {
  58. throw $e;
  59. }
  60. }
  61. }
  62. if (false === $ret) {
  63. $ret = fgets($inputStream, 4096);
  64. if (false === $ret) {
  65. throw new \RuntimeException('Aborted');
  66. }
  67. $ret = trim($ret);
  68. }
  69. } else {
  70. $ret = trim($this->autocomplete($inputStream));
  71. }
  72. $ret = strlen($ret) > 0 ? $ret : $this->question->getDefault();
  73. if ($normalizer = $this->question->getNormalizer()) {
  74. return $normalizer($ret);
  75. }
  76. return $ret;
  77. }
  78. private function autocomplete($inputStream)
  79. {
  80. $autocomplete = $this->question->getAutocompleterValues();
  81. $ret = '';
  82. $i = 0;
  83. $ofs = -1;
  84. $matches = $autocomplete;
  85. $numMatches = count($matches);
  86. $sttyMode = shell_exec('stty -g');
  87. shell_exec('stty -icanon -echo');
  88. while (!feof($inputStream)) {
  89. $c = fread($inputStream, 1);
  90. if ("\177" === $c) {
  91. if (0 === $numMatches && 0 !== $i) {
  92. --$i;
  93. $this->output->write("\033[1D");
  94. }
  95. if ($i === 0) {
  96. $ofs = -1;
  97. $matches = $autocomplete;
  98. $numMatches = count($matches);
  99. } else {
  100. $numMatches = 0;
  101. }
  102. $ret = substr($ret, 0, $i);
  103. } elseif ("\033" === $c) {
  104. $c .= fread($inputStream, 2);
  105. if (isset($c[2]) && ('A' === $c[2] || 'B' === $c[2])) {
  106. if ('A' === $c[2] && -1 === $ofs) {
  107. $ofs = 0;
  108. }
  109. if (0 === $numMatches) {
  110. continue;
  111. }
  112. $ofs += ('A' === $c[2]) ? -1 : 1;
  113. $ofs = ($numMatches + $ofs) % $numMatches;
  114. }
  115. } elseif (ord($c) < 32) {
  116. if ("\t" === $c || "\n" === $c) {
  117. if ($numMatches > 0 && -1 !== $ofs) {
  118. $ret = $matches[$ofs];
  119. $this->output->write(substr($ret, $i));
  120. $i = strlen($ret);
  121. }
  122. if ("\n" === $c) {
  123. $this->output->write($c);
  124. break;
  125. }
  126. $numMatches = 0;
  127. }
  128. continue;
  129. } else {
  130. $this->output->write($c);
  131. $ret .= $c;
  132. ++$i;
  133. $numMatches = 0;
  134. $ofs = 0;
  135. foreach ($autocomplete as $value) {
  136. if (0 === strpos($value, $ret) && $i !== strlen($value)) {
  137. $matches[$numMatches++] = $value;
  138. }
  139. }
  140. }
  141. $this->output->write("\033[K");
  142. if ($numMatches > 0 && -1 !== $ofs) {
  143. $this->output->write("\0337");
  144. $this->output->highlight(substr($matches[$ofs], $i));
  145. $this->output->write("\0338");
  146. }
  147. }
  148. shell_exec(sprintf('stty %s', $sttyMode));
  149. return $ret;
  150. }
  151. protected function getHiddenResponse($inputStream)
  152. {
  153. if ('\\' === DIRECTORY_SEPARATOR) {
  154. $exe = __DIR__ . '/../bin/hiddeninput.exe';
  155. $value = rtrim(shell_exec($exe));
  156. $this->output->writeln('');
  157. if (isset($tmpExe)) {
  158. unlink($tmpExe);
  159. }
  160. return $value;
  161. }
  162. if ($this->hasSttyAvailable()) {
  163. $sttyMode = shell_exec('stty -g');
  164. shell_exec('stty -echo');
  165. $value = fgets($inputStream, 4096);
  166. shell_exec(sprintf('stty %s', $sttyMode));
  167. if (false === $value) {
  168. throw new \RuntimeException('Aborted');
  169. }
  170. $value = trim($value);
  171. $this->output->writeln('');
  172. return $value;
  173. }
  174. if (false !== $shell = $this->getShell()) {
  175. $readCmd = $shell === 'csh' ? 'set mypassword = $<' : 'read -r mypassword';
  176. $command = sprintf("/usr/bin/env %s -c 'stty -echo; %s; stty echo; echo \$mypassword'", $shell, $readCmd);
  177. $value = rtrim(shell_exec($command));
  178. $this->output->writeln('');
  179. return $value;
  180. }
  181. throw new \RuntimeException('Unable to hide the response.');
  182. }
  183. protected function validateAttempts($interviewer)
  184. {
  185. /** @var \Exception $error */
  186. $error = null;
  187. $attempts = $this->question->getMaxAttempts();
  188. while (null === $attempts || $attempts--) {
  189. if (null !== $error) {
  190. $this->output->error($error->getMessage());
  191. }
  192. try {
  193. return call_user_func($this->question->getValidator(), $interviewer());
  194. } catch (\Exception $error) {
  195. }
  196. }
  197. throw $error;
  198. }
  199. /**
  200. * 显示问题的提示信息
  201. */
  202. protected function writePrompt()
  203. {
  204. $text = $this->question->getQuestion();
  205. $default = $this->question->getDefault();
  206. switch (true) {
  207. case null === $default:
  208. $text = sprintf(' <info>%s</info>:', $text);
  209. break;
  210. case $this->question instanceof Confirmation:
  211. $text = sprintf(' <info>%s (yes/no)</info> [<comment>%s</comment>]:', $text, $default ? 'yes' : 'no');
  212. break;
  213. case $this->question instanceof Choice && $this->question->isMultiselect():
  214. $choices = $this->question->getChoices();
  215. $default = explode(',', $default);
  216. foreach ($default as $key => $value) {
  217. $default[$key] = $choices[trim($value)];
  218. }
  219. $text = sprintf(' <info>%s</info> [<comment>%s</comment>]:', $text, implode(', ', $default));
  220. break;
  221. case $this->question instanceof Choice:
  222. $choices = $this->question->getChoices();
  223. $text = sprintf(' <info>%s</info> [<comment>%s</comment>]:', $text, $choices[$default]);
  224. break;
  225. default:
  226. $text = sprintf(' <info>%s</info> [<comment>%s</comment>]:', $text, $default);
  227. }
  228. $this->output->writeln($text);
  229. if ($this->question instanceof Choice) {
  230. $width = max(array_map('strlen', array_keys($this->question->getChoices())));
  231. foreach ($this->question->getChoices() as $key => $value) {
  232. $this->output->writeln(sprintf(" [<comment>%-${width}s</comment>] %s", $key, $value));
  233. }
  234. }
  235. $this->output->write(' > ');
  236. }
  237. private function getShell()
  238. {
  239. if (null !== self::$shell) {
  240. return self::$shell;
  241. }
  242. self::$shell = false;
  243. if (file_exists('/usr/bin/env')) {
  244. $test = "/usr/bin/env %s -c 'echo OK' 2> /dev/null";
  245. foreach (['bash', 'zsh', 'ksh', 'csh'] as $sh) {
  246. if ('OK' === rtrim(shell_exec(sprintf($test, $sh)))) {
  247. self::$shell = $sh;
  248. break;
  249. }
  250. }
  251. }
  252. return self::$shell;
  253. }
  254. private function hasSttyAvailable()
  255. {
  256. if (null !== self::$stty) {
  257. return self::$stty;
  258. }
  259. exec('stty 2>&1', $output, $exitcode);
  260. return self::$stty = $exitcode === 0;
  261. }
  262. }