Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

1023 lines
36KB

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