BaseConsole.php 39 KB

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