Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

961 Zeilen
33KB

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