BaseConsole.php 38 KB

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