BaseConsole.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\helpers;
  8. /**
  9. * BaseConsole provides concrete implementation for [[Console]].
  10. *
  11. * Do not use BaseConsole. Use [[Console]] instead.
  12. *
  13. * @author Carsten Brandt <[email protected]>
  14. * @since 2.0
  15. */
  16. class BaseConsole
  17. {
  18. const FG_BLACK = 30;
  19. const FG_RED = 31;
  20. const FG_GREEN = 32;
  21. const FG_YELLOW = 33;
  22. const FG_BLUE = 34;
  23. const FG_PURPLE = 35;
  24. const FG_CYAN = 36;
  25. const FG_GREY = 37;
  26. const BG_BLACK = 40;
  27. const BG_RED = 41;
  28. const BG_GREEN = 42;
  29. const BG_YELLOW = 43;
  30. const BG_BLUE = 44;
  31. const BG_PURPLE = 45;
  32. const BG_CYAN = 46;
  33. const BG_GREY = 47;
  34. const RESET = 0;
  35. const NORMAL = 0;
  36. const BOLD = 1;
  37. const ITALIC = 3;
  38. const UNDERLINE = 4;
  39. const BLINK = 5;
  40. const NEGATIVE = 7;
  41. const CONCEALED = 8;
  42. const CROSSED_OUT = 9;
  43. const FRAMED = 51;
  44. const ENCIRCLED = 52;
  45. const OVERLINED = 53;
  46. /**
  47. * Moves the terminal cursor up by sending ANSI control code CUU to the terminal.
  48. * If the cursor is already at the edge of the screen, this has no effect.
  49. * @param integer $rows number of rows the cursor should be moved up
  50. */
  51. public static function moveCursorUp($rows = 1)
  52. {
  53. echo "\033[" . (int)$rows . 'A';
  54. }
  55. /**
  56. * Moves the terminal cursor down by sending ANSI control code CUD to the terminal.
  57. * If the cursor is already at the edge of the screen, this has no effect.
  58. * @param integer $rows number of rows the cursor should be moved down
  59. */
  60. public static function moveCursorDown($rows = 1)
  61. {
  62. echo "\033[" . (int)$rows . 'B';
  63. }
  64. /**
  65. * Moves the terminal cursor forward by sending ANSI control code CUF to the terminal.
  66. * If the cursor is already at the edge of the screen, this has no effect.
  67. * @param integer $steps number of steps the cursor should be moved forward
  68. */
  69. public static function moveCursorForward($steps = 1)
  70. {
  71. echo "\033[" . (int)$steps . 'C';
  72. }
  73. /**
  74. * Moves the terminal cursor backward by sending ANSI control code CUB to the terminal.
  75. * If the cursor is already at the edge of the screen, this has no effect.
  76. * @param integer $steps number of steps the cursor should be moved backward
  77. */
  78. public static function moveCursorBackward($steps = 1)
  79. {
  80. echo "\033[" . (int)$steps . 'D';
  81. }
  82. /**
  83. * Moves the terminal cursor to the beginning of the next line by sending ANSI control code CNL to the terminal.
  84. * @param integer $lines number of lines the cursor should be moved down
  85. */
  86. public static function moveCursorNextLine($lines = 1)
  87. {
  88. echo "\033[" . (int)$lines . 'E';
  89. }
  90. /**
  91. * Moves the terminal cursor to the beginning of the previous line by sending ANSI control code CPL to the terminal.
  92. * @param integer $lines number of lines the cursor should be moved up
  93. */
  94. public static function moveCursorPrevLine($lines = 1)
  95. {
  96. echo "\033[" . (int)$lines . 'F';
  97. }
  98. /**
  99. * Moves the cursor to an absolute position given as column and row by sending ANSI control code CUP or CHA to the terminal.
  100. * @param integer $column 1-based column number, 1 is the left edge of the screen.
  101. * @param integer|null $row 1-based row number, 1 is the top edge of the screen. if not set, will move cursor only in current line.
  102. */
  103. public static function moveCursorTo($column, $row = null)
  104. {
  105. if ($row === null) {
  106. echo "\033[" . (int)$column . 'G';
  107. } else {
  108. echo "\033[" . (int)$row . ';' . (int)$column . 'H';
  109. }
  110. }
  111. /**
  112. * Scrolls whole page up by sending ANSI control code SU to the terminal.
  113. * New lines are added at the bottom. This is not supported by ANSI.SYS used in windows.
  114. * @param int $lines number of lines to scroll up
  115. */
  116. public static function scrollUp($lines = 1)
  117. {
  118. echo "\033[" . (int)$lines . "S";
  119. }
  120. /**
  121. * Scrolls whole page down by sending ANSI control code SD to the terminal.
  122. * New lines are added at the top. This is not supported by ANSI.SYS used in windows.
  123. * @param int $lines number of lines to scroll down
  124. */
  125. public static function scrollDown($lines = 1)
  126. {
  127. echo "\033[" . (int)$lines . "T";
  128. }
  129. /**
  130. * Saves the current cursor position by sending ANSI control code SCP to the terminal.
  131. * Position can then be restored with [[restoreCursorPosition()]].
  132. */
  133. public static function saveCursorPosition()
  134. {
  135. echo "\033[s";
  136. }
  137. /**
  138. * Restores the cursor position saved with [[saveCursorPosition()]] by sending ANSI control code RCP to the terminal.
  139. */
  140. public static function restoreCursorPosition()
  141. {
  142. echo "\033[u";
  143. }
  144. /**
  145. * Hides the cursor by sending ANSI DECTCEM code ?25l to the terminal.
  146. * Use [[showCursor()]] to bring it back.
  147. * Do not forget to show cursor when your application exits. Cursor might stay hidden in terminal after exit.
  148. */
  149. public static function hideCursor()
  150. {
  151. echo "\033[?25l";
  152. }
  153. /**
  154. * Will show a cursor again when it has been hidden by [[hideCursor()]] by sending ANSI DECTCEM code ?25h to the terminal.
  155. */
  156. public static function showCursor()
  157. {
  158. echo "\033[?25h";
  159. }
  160. /**
  161. * Clears entire screen content by sending ANSI control code ED with argument 2 to the terminal.
  162. * Cursor position will not be changed.
  163. * **Note:** ANSI.SYS implementation used in windows will reset cursor position to upper left corner of the screen.
  164. */
  165. public static function clearScreen()
  166. {
  167. echo "\033[2J";
  168. }
  169. /**
  170. * Clears text from cursor to the beginning of the screen by sending ANSI control code ED with argument 1 to the terminal.
  171. * Cursor position will not be changed.
  172. */
  173. public static function clearScreenBeforeCursor()
  174. {
  175. echo "\033[1J";
  176. }
  177. /**
  178. * Clears text from cursor to the end of the screen by sending ANSI control code ED with argument 0 to the terminal.
  179. * Cursor position will not be changed.
  180. */
  181. public static function clearScreenAfterCursor()
  182. {
  183. echo "\033[0J";
  184. }
  185. /**
  186. * Clears the line, the cursor is currently on by sending ANSI control code EL with argument 2 to the terminal.
  187. * Cursor position will not be changed.
  188. */
  189. public static function clearLine()
  190. {
  191. echo "\033[2K";
  192. }
  193. /**
  194. * Clears text from cursor position to the beginning of the line by sending ANSI control code EL with argument 1 to the terminal.
  195. * Cursor position will not be changed.
  196. */
  197. public static function clearLineBeforeCursor()
  198. {
  199. echo "\033[1K";
  200. }
  201. /**
  202. * Clears text from cursor position to the end of the line by sending ANSI control code EL with argument 0 to the terminal.
  203. * Cursor position will not be changed.
  204. */
  205. public static function clearLineAfterCursor()
  206. {
  207. echo "\033[0K";
  208. }
  209. /**
  210. * Returns the ANSI format code.
  211. *
  212. * @param array $format An array containing formatting values.
  213. * You can pass any of the FG_*, BG_* and TEXT_* constants
  214. * and also [[xtermFgColor]] and [[xtermBgColor]] to specify a format.
  215. * @return string The ANSI format code according to the given formatting constants.
  216. */
  217. public static function ansiFormatCode($format)
  218. {
  219. return "\033[" . implode(';', $format) . 'm';
  220. }
  221. /**
  222. * Echoes an ANSI format code that affects the formatting of any text that is printed afterwards.
  223. *
  224. * @param array $format An array containing formatting values.
  225. * You can pass any of the FG_*, BG_* and TEXT_* constants
  226. * and also [[xtermFgColor]] and [[xtermBgColor]] to specify a format.
  227. * @see ansiFormatCode()
  228. * @see ansiFormatEnd()
  229. */
  230. public static function beginAnsiFormat($format)
  231. {
  232. echo "\033[" . implode(';', $format) . 'm';
  233. }
  234. /**
  235. * Resets any ANSI format set by previous method [[ansiFormatBegin()]]
  236. * Any output after this will have default text format.
  237. * This is equal to calling
  238. *
  239. * ```php
  240. * echo Console::ansiFormatCode([Console::RESET])
  241. * ```
  242. */
  243. public static function endAnsiFormat()
  244. {
  245. echo "\033[0m";
  246. }
  247. /**
  248. * Will return a string formatted with the given ANSI style
  249. *
  250. * @param string $string the string to be formatted
  251. * @param array $format An array containing formatting values.
  252. * You can pass any of the FG_*, BG_* and TEXT_* constants
  253. * and also [[xtermFgColor]] and [[xtermBgColor]] to specify a format.
  254. * @return string
  255. */
  256. public static function ansiFormat($string, $format = [])
  257. {
  258. $code = implode(';', $format);
  259. return "\033[0m" . ($code !== '' ? "\033[" . $code . "m" : '') . $string . "\033[0m";
  260. }
  261. /**
  262. * Returns the ansi format code for xterm foreground color.
  263. * You can pass the return value of this to one of the formatting methods:
  264. * [[ansiFormat]], [[ansiFormatCode]], [[beginAnsiFormat]]
  265. *
  266. * @param integer $colorCode xterm color code
  267. * @return string
  268. * @see http://en.wikipedia.org/wiki/Talk:ANSI_escape_code#xterm-256colors
  269. */
  270. public static function xtermFgColor($colorCode)
  271. {
  272. return '38;5;' . $colorCode;
  273. }
  274. /**
  275. * Returns the ansi format code for xterm background color.
  276. * You can pass the return value of this to one of the formatting methods:
  277. * [[ansiFormat]], [[ansiFormatCode]], [[beginAnsiFormat]]
  278. *
  279. * @param integer $colorCode xterm color code
  280. * @return string
  281. * @see http://en.wikipedia.org/wiki/Talk:ANSI_escape_code#xterm-256colors
  282. */
  283. public static function xtermBgColor($colorCode)
  284. {
  285. return '48;5;' . $colorCode;
  286. }
  287. /**
  288. * Strips ANSI control codes from a string
  289. *
  290. * @param string $string String to strip
  291. * @return string
  292. */
  293. public static function stripAnsiFormat($string)
  294. {
  295. return preg_replace('/\033\[[\d;?]*\w/', '', $string);
  296. }
  297. /**
  298. * Converts an ANSI formatted string to HTML
  299. * @param $string
  300. * @return mixed
  301. */
  302. // TODO rework/refactor according to https://github.com/yiisoft/yii2/issues/746
  303. public static function ansiToHtml($string)
  304. {
  305. $tags = 0;
  306. return preg_replace_callback(
  307. '/\033\[[\d;]+m/',
  308. function ($ansi) use (&$tags) {
  309. $styleA = [];
  310. foreach (explode(';', $ansi) as $controlCode) {
  311. switch ($controlCode) {
  312. case self::FG_BLACK:
  313. $style = ['color' => '#000000'];
  314. break;
  315. case self::FG_BLUE:
  316. $style = ['color' => '#000078'];
  317. break;
  318. case self::FG_CYAN:
  319. $style = ['color' => '#007878'];
  320. break;
  321. case self::FG_GREEN:
  322. $style = ['color' => '#007800'];
  323. break;
  324. case self::FG_GREY:
  325. $style = ['color' => '#787878'];
  326. break;
  327. case self::FG_PURPLE:
  328. $style = ['color' => '#780078'];
  329. break;
  330. case self::FG_RED:
  331. $style = ['color' => '#780000'];
  332. break;
  333. case self::FG_YELLOW:
  334. $style = ['color' => '#787800'];
  335. break;
  336. case self::BG_BLACK:
  337. $style = ['background-color' => '#000000'];
  338. break;
  339. case self::BG_BLUE:
  340. $style = ['background-color' => '#000078'];
  341. break;
  342. case self::BG_CYAN:
  343. $style = ['background-color' => '#007878'];
  344. break;
  345. case self::BG_GREEN:
  346. $style = ['background-color' => '#007800'];
  347. break;
  348. case self::BG_GREY:
  349. $style = ['background-color' => '#787878'];
  350. break;
  351. case self::BG_PURPLE:
  352. $style = ['background-color' => '#780078'];
  353. break;
  354. case self::BG_RED:
  355. $style = ['background-color' => '#780000'];
  356. break;
  357. case self::BG_YELLOW:
  358. $style = ['background-color' => '#787800'];
  359. break;
  360. case self::BOLD:
  361. $style = ['font-weight' => 'bold'];
  362. break;
  363. case self::ITALIC:
  364. $style = ['font-style' => 'italic'];
  365. break;
  366. case self::UNDERLINE:
  367. $style = ['text-decoration' => ['underline']];
  368. break;
  369. case self::OVERLINED:
  370. $style = ['text-decoration' => ['overline']];
  371. break;
  372. case self::CROSSED_OUT:
  373. $style = ['text-decoration' => ['line-through']];
  374. break;
  375. case self::BLINK:
  376. $style = ['text-decoration' => ['blink']];
  377. break;
  378. case self::NEGATIVE: // ???
  379. case self::CONCEALED:
  380. case self::ENCIRCLED:
  381. case self::FRAMED:
  382. // TODO allow resetting codes
  383. break;
  384. case 0: // ansi reset
  385. $return = '';
  386. for ($n = $tags; $tags > 0; $tags--) {
  387. $return .= '</span>';
  388. }
  389. return $return;
  390. }
  391. $styleA = ArrayHelper::merge($styleA, $style);
  392. }
  393. $styleString[] = [];
  394. foreach ($styleA as $name => $content) {
  395. if ($name === 'text-decoration') {
  396. $content = implode(' ', $content);
  397. }
  398. $styleString[] = $name . ':' . $content;
  399. }
  400. $tags++;
  401. return '<span' . (!empty($styleString) ? 'style="' . implode(';', $styleString) : '') . '>';
  402. },
  403. $string
  404. );
  405. }
  406. // TODO rework/refactor according to https://github.com/yiisoft/yii2/issues/746
  407. public function markdownToAnsi()
  408. {
  409. // TODO implement
  410. }
  411. /**
  412. * Converts a string to ansi formatted by replacing patterns like %y (for yellow) with ansi control codes
  413. *
  414. * Uses almost the same syntax as https://github.com/pear/Console_Color2/blob/master/Console/Color2.php
  415. * The conversion table is: ('bold' meaning 'light' on some
  416. * terminals). It's almost the same conversion table irssi uses.
  417. * <pre>
  418. * text text background
  419. * ------------------------------------------------
  420. * %k %K %0 black dark grey black
  421. * %r %R %1 red bold red red
  422. * %g %G %2 green bold green green
  423. * %y %Y %3 yellow bold yellow yellow
  424. * %b %B %4 blue bold blue blue
  425. * %m %M %5 magenta bold magenta magenta
  426. * %p %P magenta (think: purple)
  427. * %c %C %6 cyan bold cyan cyan
  428. * %w %W %7 white bold white white
  429. *
  430. * %F Blinking, Flashing
  431. * %U Underline
  432. * %8 Reverse
  433. * %_,%9 Bold
  434. *
  435. * %n Resets the color
  436. * %% A single %
  437. * </pre>
  438. * First param is the string to convert, second is an optional flag if
  439. * colors should be used. It defaults to true, if set to false, the
  440. * colorcodes will just be removed (And %% will be transformed into %)
  441. *
  442. * @param string $string String to convert
  443. * @param bool $colored Should the string be colored?
  444. * @return string
  445. */
  446. // TODO rework/refactor according to https://github.com/yiisoft/yii2/issues/746
  447. public static function renderColoredString($string, $colored = true)
  448. {
  449. static $conversions = [
  450. '%y' => [self::FG_YELLOW],
  451. '%g' => [self::FG_GREEN],
  452. '%b' => [self::FG_BLUE],
  453. '%r' => [self::FG_RED],
  454. '%p' => [self::FG_PURPLE],
  455. '%m' => [self::FG_PURPLE],
  456. '%c' => [self::FG_CYAN],
  457. '%w' => [self::FG_GREY],
  458. '%k' => [self::FG_BLACK],
  459. '%n' => [0], // reset
  460. '%Y' => [self::FG_YELLOW, self::BOLD],
  461. '%G' => [self::FG_GREEN, self::BOLD],
  462. '%B' => [self::FG_BLUE, self::BOLD],
  463. '%R' => [self::FG_RED, self::BOLD],
  464. '%P' => [self::FG_PURPLE, self::BOLD],
  465. '%M' => [self::FG_PURPLE, self::BOLD],
  466. '%C' => [self::FG_CYAN, self::BOLD],
  467. '%W' => [self::FG_GREY, self::BOLD],
  468. '%K' => [self::FG_BLACK, self::BOLD],
  469. '%N' => [0, self::BOLD],
  470. '%3' => [self::BG_YELLOW],
  471. '%2' => [self::BG_GREEN],
  472. '%4' => [self::BG_BLUE],
  473. '%1' => [self::BG_RED],
  474. '%5' => [self::BG_PURPLE],
  475. '%6' => [self::BG_PURPLE],
  476. '%7' => [self::BG_CYAN],
  477. '%0' => [self::BG_GREY],
  478. '%F' => [self::BLINK],
  479. '%U' => [self::UNDERLINE],
  480. '%8' => [self::NEGATIVE],
  481. '%9' => [self::BOLD],
  482. '%_' => [self::BOLD],
  483. ];
  484. if ($colored) {
  485. $string = str_replace('%%', '% ', $string);
  486. foreach ($conversions as $key => $value) {
  487. $string = str_replace(
  488. $key,
  489. static::ansiFormatCode($value),
  490. $string
  491. );
  492. }
  493. $string = str_replace('% ', '%', $string);
  494. } else {
  495. $string = preg_replace('/%((%)|.)/', '$2', $string);
  496. }
  497. return $string;
  498. }
  499. /**
  500. * Escapes % so they don't get interpreted as color codes when
  501. * the string is parsed by [[renderColoredString]]
  502. *
  503. * @param string $string String to escape
  504. *
  505. * @access public
  506. * @return string
  507. */
  508. // TODO rework/refactor according to https://github.com/yiisoft/yii2/issues/746
  509. public static function escape($string)
  510. {
  511. return str_replace('%', '%%', $string);
  512. }
  513. /**
  514. * Returns true if the stream supports colorization. ANSI colors are disabled if not supported by the stream.
  515. *
  516. * - windows without ansicon
  517. * - not tty consoles
  518. *
  519. * @param mixed $stream
  520. * @return bool true if the stream supports ANSI colors, otherwise false.
  521. */
  522. public static function streamSupportsAnsiColors($stream)
  523. {
  524. return DIRECTORY_SEPARATOR == '\\'
  525. ? getenv('ANSICON') !== false || getenv('ConEmuANSI') === 'ON'
  526. : function_exists('posix_isatty') && @posix_isatty($stream);
  527. }
  528. /**
  529. * Returns true if the console is running on windows
  530. * @return bool
  531. */
  532. public static function isRunningOnWindows()
  533. {
  534. return DIRECTORY_SEPARATOR == '\\';
  535. }
  536. /**
  537. * Usage: list($width, $height) = ConsoleHelper::getScreenSize();
  538. *
  539. * @param bool $refresh whether to force checking and not re-use cached size value.
  540. * This is useful to detect changing window size while the application is running but may
  541. * not get up to date values on every terminal.
  542. * @return array|boolean An array of ($width, $height) or false when it was not able to determine size.
  543. */
  544. public static function getScreenSize($refresh = false)
  545. {
  546. static $size;
  547. if ($size !== null && !$refresh) {
  548. return $size;
  549. }
  550. if (static::isRunningOnWindows()) {
  551. $output = [];
  552. exec('mode con', $output);
  553. if (isset($output) && strpos($output[1], 'CON') !== false) {
  554. return $size = [(int)preg_replace('~[^0-9]~', '', $output[3]), (int)preg_replace('~[^0-9]~', '', $output[4])];
  555. }
  556. } else {
  557. // try stty if available
  558. $stty = [];
  559. if (exec('stty -a 2>&1', $stty) && preg_match('/rows\s+(\d+);\s*columns\s+(\d+);/mi', implode(' ', $stty), $matches)) {
  560. return $size = [$matches[2], $matches[1]];
  561. }
  562. // fallback to tput, which may not be updated on terminal resize
  563. if (($width = (int) exec('tput cols 2>&1')) > 0 && ($height = (int) exec('tput lines 2>&1')) > 0) {
  564. return $size = [$width, $height];
  565. }
  566. // fallback to ENV variables, which may not be updated on terminal resize
  567. if (($width = (int) getenv('COLUMNS')) > 0 && ($height = (int) getenv('LINES')) > 0) {
  568. return $size = [$width, $height];
  569. }
  570. }
  571. return $size = false;
  572. }
  573. /**
  574. * Gets input from STDIN and returns a string right-trimmed for EOLs.
  575. *
  576. * @param bool $raw If set to true, returns the raw string without trimming
  577. * @return string the string read from stdin
  578. */
  579. public static function stdin($raw = false)
  580. {
  581. return $raw ? fgets(STDIN) : rtrim(fgets(STDIN), PHP_EOL);
  582. }
  583. /**
  584. * Prints a string to STDOUT.
  585. *
  586. * @param string $string the string to print
  587. * @return int|boolean Number of bytes printed or false on error
  588. */
  589. public static function stdout($string)
  590. {
  591. return fwrite(STDOUT, $string);
  592. }
  593. /**
  594. * Prints a string to STDERR.
  595. *
  596. * @param string $string the string to print
  597. * @return int|boolean Number of bytes printed or false on error
  598. */
  599. public static function stderr($string)
  600. {
  601. return fwrite(STDERR, $string);
  602. }
  603. /**
  604. * Asks the user for input. Ends when the user types a carriage return (PHP_EOL). Optionally, It also provides a
  605. * prompt.
  606. *
  607. * @param string $prompt the prompt to display before waiting for input (optional)
  608. * @return string the user's input
  609. */
  610. public static function input($prompt = null)
  611. {
  612. if (isset($prompt)) {
  613. static::stdout($prompt);
  614. }
  615. return static::stdin();
  616. }
  617. /**
  618. * Prints text to STDOUT appended with a carriage return (PHP_EOL).
  619. *
  620. * @param string $string the text to print
  621. * @return integer|boolean number of bytes printed or false on error.
  622. */
  623. public static function output($string = null)
  624. {
  625. return static::stdout($string . PHP_EOL);
  626. }
  627. /**
  628. * Prints text to STDERR appended with a carriage return (PHP_EOL).
  629. *
  630. * @param string $string the text to print
  631. * @return integer|boolean number of bytes printed or false on error.
  632. */
  633. public static function error($string = null)
  634. {
  635. return static::stderr($string . PHP_EOL);
  636. }
  637. /**
  638. * Prompts the user for input and validates it
  639. *
  640. * @param string $text prompt string
  641. * @param array $options the options to validate the input:
  642. * - required: whether it is required or not
  643. * - default: default value if no input is inserted by the user
  644. * - pattern: regular expression pattern to validate user input
  645. * - validator: a callable function to validate input. The function must accept two parameters:
  646. * - $input: the user input to validate
  647. * - $error: the error value passed by reference if validation failed.
  648. * @return string the user input
  649. */
  650. public static function prompt($text, $options = [])
  651. {
  652. $options = ArrayHelper::merge(
  653. [
  654. 'required' => false,
  655. 'default' => null,
  656. 'pattern' => null,
  657. 'validator' => null,
  658. 'error' => 'Invalid input.',
  659. ],
  660. $options
  661. );
  662. $error = null;
  663. top:
  664. $input = $options['default']
  665. ? static::input("$text [" . $options['default'] . ']: ')
  666. : static::input("$text: ");
  667. if (!strlen($input)) {
  668. if (isset($options['default'])) {
  669. $input = $options['default'];
  670. } elseif ($options['required']) {
  671. static::output($options['error']);
  672. goto top;
  673. }
  674. } elseif ($options['pattern'] && !preg_match($options['pattern'], $input)) {
  675. static::output($options['error']);
  676. goto top;
  677. } elseif ($options['validator'] &&
  678. !call_user_func_array($options['validator'], [$input, &$error])
  679. ) {
  680. static::output(isset($error) ? $error : $options['error']);
  681. goto top;
  682. }
  683. return $input;
  684. }
  685. /**
  686. * Asks user to confirm by typing y or n.
  687. *
  688. * @param string $message to echo out before waiting for user input
  689. * @param boolean $default this value is returned if no selection is made.
  690. * @return boolean whether user confirmed
  691. */
  692. public static function confirm($message, $default = true)
  693. {
  694. echo $message . ' (yes|no) [' . ($default ? 'yes' : 'no') . ']:';
  695. $input = trim(static::stdin());
  696. return empty($input) ? $default : !strncasecmp($input, 'y', 1);
  697. }
  698. /**
  699. * Gives the user an option to choose from. Giving '?' as an input will show
  700. * a list of options to choose from and their explanations.
  701. *
  702. * @param string $prompt the prompt message
  703. * @param array $options Key-value array of options to choose from
  704. *
  705. * @return string An option character the user chose
  706. */
  707. public static function select($prompt, $options = [])
  708. {
  709. top:
  710. static::stdout("$prompt [" . implode(',', array_keys($options)) . ",?]: ");
  711. $input = static::stdin();
  712. if ($input === '?') {
  713. foreach ($options as $key => $value) {
  714. static::output(" $key - $value");
  715. }
  716. static::output(" ? - Show help");
  717. goto top;
  718. } elseif (!in_array($input, array_keys($options))) {
  719. goto top;
  720. }
  721. return $input;
  722. }
  723. private static $_progressStart;
  724. private static $_progressWidth;
  725. private static $_progressPrefix;
  726. /**
  727. * Starts display of a progress bar on screen.
  728. *
  729. * This bar will be updated by [[updateProgress()]] and my be ended by [[endProgress()]].
  730. *
  731. * The following example shows a simple usage of a progress bar:
  732. *
  733. * ```php
  734. * Console::startProgress(0, 1000);
  735. * for ($n = 1; $n <= 1000; $n++) {
  736. * usleep(1000);
  737. * Console::updateProgress($n, 1000);
  738. * }
  739. * Console::endProgress();
  740. * ```
  741. *
  742. * Git clone like progress (showing only status information):
  743. * ```php
  744. * Console::startProgress(0, 1000, 'Counting objects: ', false);
  745. * for ($n = 1; $n <= 1000; $n++) {
  746. * usleep(1000);
  747. * Console::updateProgress($n, 1000);
  748. * }
  749. * Console::endProgress("done." . PHP_EOL);
  750. * ```
  751. *
  752. * @param integer $done the number of items that are completed.
  753. * @param integer $total the total value of items that are to be done.
  754. * @param string $prefix an optional string to display before the progress bar.
  755. * Default to empty string which results in no prefix to be displayed.
  756. * @param integer|boolean $width optional width of the progressbar. This can be an integer representing
  757. * the number of characters to display for the progress bar or a float between 0 and 1 representing the
  758. * percentage of screen with the progress bar may take. It can also be set to false to disable the
  759. * bar and only show progress information like percent, number of items and ETA.
  760. * If not set, the bar will be as wide as the screen. Screen size will be detected using [[getScreenSize()]].
  761. * @see startProgress
  762. * @see updateProgress
  763. * @see endProgress
  764. */
  765. public static function startProgress($done, $total, $prefix = '', $width = null)
  766. {
  767. self::$_progressStart = time();
  768. self::$_progressWidth = $width;
  769. self::$_progressPrefix = $prefix;
  770. static::updateProgress($done, $total);
  771. }
  772. /**
  773. * Updates a progress bar that has been started by [[startProgress()]].
  774. *
  775. * @param integer $done the number of items that are completed.
  776. * @param integer $total the total value of items that are to be done.
  777. * @param string $prefix an optional string to display before the progress bar.
  778. * Defaults to null meaning the prefix specified by [[startProgress()]] will be used.
  779. * If prefix is specified it will update the prefix that will be used by later calls.
  780. * @see startProgress
  781. * @see endProgress
  782. */
  783. public static function updateProgress($done, $total, $prefix = null)
  784. {
  785. $width = self::$_progressWidth;
  786. if ($width === false) {
  787. $width = 0;
  788. } else {
  789. $screenSize = static::getScreenSize(true);
  790. if ($screenSize === false && $width < 1) {
  791. $width = 0;
  792. } elseif ($width === null) {
  793. $width = $screenSize[0];
  794. } elseif ($width > 0 && $width < 1) {
  795. $width = floor($screenSize[0] * $width);
  796. }
  797. }
  798. if ($prefix === null) {
  799. $prefix = self::$_progressPrefix;
  800. } else {
  801. self::$_progressPrefix = $prefix;
  802. }
  803. $width -= mb_strlen($prefix);
  804. $percent = ($total == 0) ? 1 : $done / $total;
  805. $info = sprintf("%d%% (%d/%d)", $percent * 100, $done, $total);
  806. if ($done > $total || $done == 0) {
  807. $info .= ' ETA: n/a';
  808. } elseif ($done < $total) {
  809. $rate = (time() - self::$_progressStart) / $done;
  810. $info .= sprintf(' ETA: %d sec.', $rate * ($total - $done));
  811. }
  812. $width -= 3 + mb_strlen($info);
  813. // skipping progress bar on very small display or if forced to skip
  814. if ($width < 5) {
  815. static::stdout("\r$prefix$info ");
  816. } else {
  817. if ($percent < 0) {
  818. $percent = 0;
  819. } elseif ($percent > 1) {
  820. $percent = 1;
  821. }
  822. $bar = floor($percent * $width);
  823. $status = str_repeat("=", $bar);
  824. if ($bar < $width) {
  825. $status .= ">";
  826. $status .= str_repeat(" ", $width - $bar - 1);
  827. }
  828. static::stdout("\r$prefix" . "[$status] $info");
  829. }
  830. flush();
  831. }
  832. /**
  833. * Ends a progress bar that has been started by [[startProgress()]].
  834. *
  835. * @param string|boolean $remove This can be `false` to leave the progress bar on screen and just print a newline.
  836. * If set to `true`, the line of the progress bar will be cleared. This may also be a string to be displayed instead
  837. * of the progress bar.
  838. * @param bool $keepPrefix whether to keep the prefix that has been specified for the progressbar when progressbar
  839. * gets removed. Defaults to true.
  840. * @see startProgress
  841. * @see updateProgress
  842. */
  843. public static function endProgress($remove = false, $keepPrefix = true)
  844. {
  845. if ($remove === false) {
  846. static::stdout(PHP_EOL);
  847. } else {
  848. if (static::streamSupportsAnsiColors(STDOUT)) {
  849. static::clearLine();
  850. }
  851. static::stdout("\r" . ($keepPrefix ? self::$_progressPrefix : '') . (is_string($remove) ? $remove : ''));
  852. }
  853. flush();
  854. self::$_progressStart = null;
  855. self::$_progressWidth = null;
  856. self::$_progressPrefix = '';
  857. }
  858. }