BaseConsole.php 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195
  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(self::ansiCodesPattern(), '', $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. * Returns the portion with ANSI color codes of string specified by the start and length parameters.
  326. * If string has color codes, then will be return "TEXT_COLOR + TEXT_STRING + DEFAULT_COLOR",
  327. * else will be simple "TEXT_STRING".
  328. * @param string $string
  329. * @param int $start
  330. * @param int $length
  331. * @return string
  332. */
  333. public static function ansiColorizedSubstr($string, $start, $length)
  334. {
  335. if ($start < 0 || $length <= 0) {
  336. return '';
  337. }
  338. $textItems = preg_split(self::ansiCodesPattern(), $string);
  339. preg_match_all(self::ansiCodesPattern(), $string, $colors);
  340. $colors = count($colors) ? $colors[0] : [];
  341. array_unshift($colors, '');
  342. $result = '';
  343. $curPos = 0;
  344. $inRange = false;
  345. foreach ($textItems as $k => $textItem) {
  346. $color = $colors[$k];
  347. if ($curPos <= $start && $start < $curPos + Console::ansiStrwidth($textItem)) {
  348. $text = mb_substr($textItem, $start - $curPos, null, Yii::$app->charset);
  349. $inRange = true;
  350. } else {
  351. $text = $textItem;
  352. }
  353. if ($inRange) {
  354. $result .= $color . $text;
  355. $diff = $length - Console::ansiStrwidth($result);
  356. if ($diff <= 0) {
  357. if ($diff < 0) {
  358. $result = mb_substr($result, 0, $diff, Yii::$app->charset);
  359. }
  360. $defaultColor = static::renderColoredString('%n');
  361. if ($color && $color != $defaultColor) {
  362. $result .= $defaultColor;
  363. }
  364. break;
  365. }
  366. }
  367. $curPos += mb_strlen($textItem, Yii::$app->charset);
  368. }
  369. return $result;
  370. }
  371. private static function ansiCodesPattern()
  372. {
  373. return /** @lang PhpRegExp */ '/\033\[[\d;?]*\w/';
  374. }
  375. /**
  376. * Converts an ANSI formatted string to HTML.
  377. *
  378. * Note: xTerm 256 bit colors are currently not supported.
  379. *
  380. * @param string $string the string to convert.
  381. * @param array $styleMap an optional mapping of ANSI control codes such as
  382. * FG\_*COLOR* or [[BOLD]] to a set of css style definitions.
  383. * The CSS style definitions are represented as an array where the array keys correspond
  384. * to the css style attribute names and the values are the css values.
  385. * values may be arrays that will be merged and imploded with `' '` when rendered.
  386. * @return string HTML representation of the ANSI formatted string
  387. */
  388. public static function ansiToHtml($string, $styleMap = [])
  389. {
  390. $styleMap = [
  391. // http://www.w3.org/TR/CSS2/syndata.html#value-def-color
  392. self::FG_BLACK => ['color' => 'black'],
  393. self::FG_BLUE => ['color' => 'blue'],
  394. self::FG_CYAN => ['color' => 'aqua'],
  395. self::FG_GREEN => ['color' => 'lime'],
  396. self::FG_GREY => ['color' => 'silver'],
  397. // http://meyerweb.com/eric/thoughts/2014/06/19/rebeccapurple/
  398. // http://dev.w3.org/csswg/css-color/#valuedef-rebeccapurple
  399. self::FG_PURPLE => ['color' => 'rebeccapurple'],
  400. self::FG_RED => ['color' => 'red'],
  401. self::FG_YELLOW => ['color' => 'yellow'],
  402. self::BG_BLACK => ['background-color' => 'black'],
  403. self::BG_BLUE => ['background-color' => 'blue'],
  404. self::BG_CYAN => ['background-color' => 'aqua'],
  405. self::BG_GREEN => ['background-color' => 'lime'],
  406. self::BG_GREY => ['background-color' => 'silver'],
  407. self::BG_PURPLE => ['background-color' => 'rebeccapurple'],
  408. self::BG_RED => ['background-color' => 'red'],
  409. self::BG_YELLOW => ['background-color' => 'yellow'],
  410. self::BOLD => ['font-weight' => 'bold'],
  411. self::ITALIC => ['font-style' => 'italic'],
  412. self::UNDERLINE => ['text-decoration' => ['underline']],
  413. self::OVERLINED => ['text-decoration' => ['overline']],
  414. self::CROSSED_OUT => ['text-decoration' => ['line-through']],
  415. self::BLINK => ['text-decoration' => ['blink']],
  416. self::CONCEALED => ['visibility' => 'hidden'],
  417. ] + $styleMap;
  418. $tags = 0;
  419. $result = preg_replace_callback(
  420. '/\033\[([\d;]+)m/',
  421. function ($ansi) use (&$tags, $styleMap) {
  422. $style = [];
  423. $reset = false;
  424. $negative = false;
  425. foreach (explode(';', $ansi[1]) as $controlCode) {
  426. if ($controlCode == 0) {
  427. $style = [];
  428. $reset = true;
  429. } elseif ($controlCode == self::NEGATIVE) {
  430. $negative = true;
  431. } elseif (isset($styleMap[$controlCode])) {
  432. $style[] = $styleMap[$controlCode];
  433. }
  434. }
  435. $return = '';
  436. while ($reset && $tags > 0) {
  437. $return .= '</span>';
  438. $tags--;
  439. }
  440. if (empty($style)) {
  441. return $return;
  442. }
  443. $currentStyle = [];
  444. foreach ($style as $content) {
  445. $currentStyle = ArrayHelper::merge($currentStyle, $content);
  446. }
  447. // if negative is set, invert background and foreground
  448. if ($negative) {
  449. if (isset($currentStyle['color'])) {
  450. $fgColor = $currentStyle['color'];
  451. unset($currentStyle['color']);
  452. }
  453. if (isset($currentStyle['background-color'])) {
  454. $bgColor = $currentStyle['background-color'];
  455. unset($currentStyle['background-color']);
  456. }
  457. if (isset($fgColor)) {
  458. $currentStyle['background-color'] = $fgColor;
  459. }
  460. if (isset($bgColor)) {
  461. $currentStyle['color'] = $bgColor;
  462. }
  463. }
  464. $styleString = '';
  465. foreach ($currentStyle as $name => $value) {
  466. if (is_array($value)) {
  467. $value = implode(' ', $value);
  468. }
  469. $styleString .= "$name: $value;";
  470. }
  471. $tags++;
  472. return "$return<span style=\"$styleString\">";
  473. },
  474. $string
  475. );
  476. while ($tags > 0) {
  477. $result .= '</span>';
  478. $tags--;
  479. }
  480. return $result;
  481. }
  482. /**
  483. * Converts Markdown to be better readable in console environments by applying some ANSI format.
  484. * @param string $markdown the markdown string.
  485. * @return string the parsed result as ANSI formatted string.
  486. */
  487. public static function markdownToAnsi($markdown)
  488. {
  489. $parser = new ConsoleMarkdown();
  490. return $parser->parse($markdown);
  491. }
  492. /**
  493. * Converts a string to ansi formatted by replacing patterns like %y (for yellow) with ansi control codes.
  494. *
  495. * Uses almost the same syntax as https://github.com/pear/Console_Color2/blob/master/Console/Color2.php
  496. * The conversion table is: ('bold' meaning 'light' on some
  497. * terminals). It's almost the same conversion table irssi uses.
  498. * <pre>
  499. * text text background
  500. * ------------------------------------------------
  501. * %k %K %0 black dark grey black
  502. * %r %R %1 red bold red red
  503. * %g %G %2 green bold green green
  504. * %y %Y %3 yellow bold yellow yellow
  505. * %b %B %4 blue bold blue blue
  506. * %m %M %5 magenta bold magenta magenta
  507. * %p %P magenta (think: purple)
  508. * %c %C %6 cyan bold cyan cyan
  509. * %w %W %7 white bold white white
  510. *
  511. * %F Blinking, Flashing
  512. * %U Underline
  513. * %8 Reverse
  514. * %_,%9 Bold
  515. *
  516. * %n Resets the color
  517. * %% A single %
  518. * </pre>
  519. * First param is the string to convert, second is an optional flag if
  520. * colors should be used. It defaults to true, if set to false, the
  521. * color codes will just be removed (And %% will be transformed into %)
  522. *
  523. * @param string $string String to convert
  524. * @param bool $colored Should the string be colored?
  525. * @return string
  526. */
  527. public static function renderColoredString($string, $colored = true)
  528. {
  529. // TODO rework/refactor according to https://github.com/yiisoft/yii2/issues/746
  530. static $conversions = [
  531. '%y' => [self::FG_YELLOW],
  532. '%g' => [self::FG_GREEN],
  533. '%b' => [self::FG_BLUE],
  534. '%r' => [self::FG_RED],
  535. '%p' => [self::FG_PURPLE],
  536. '%m' => [self::FG_PURPLE],
  537. '%c' => [self::FG_CYAN],
  538. '%w' => [self::FG_GREY],
  539. '%k' => [self::FG_BLACK],
  540. '%n' => [0], // reset
  541. '%Y' => [self::FG_YELLOW, self::BOLD],
  542. '%G' => [self::FG_GREEN, self::BOLD],
  543. '%B' => [self::FG_BLUE, self::BOLD],
  544. '%R' => [self::FG_RED, self::BOLD],
  545. '%P' => [self::FG_PURPLE, self::BOLD],
  546. '%M' => [self::FG_PURPLE, self::BOLD],
  547. '%C' => [self::FG_CYAN, self::BOLD],
  548. '%W' => [self::FG_GREY, self::BOLD],
  549. '%K' => [self::FG_BLACK, self::BOLD],
  550. '%N' => [0, self::BOLD],
  551. '%3' => [self::BG_YELLOW],
  552. '%2' => [self::BG_GREEN],
  553. '%4' => [self::BG_BLUE],
  554. '%1' => [self::BG_RED],
  555. '%5' => [self::BG_PURPLE],
  556. '%6' => [self::BG_CYAN],
  557. '%7' => [self::BG_GREY],
  558. '%0' => [self::BG_BLACK],
  559. '%F' => [self::BLINK],
  560. '%U' => [self::UNDERLINE],
  561. '%8' => [self::NEGATIVE],
  562. '%9' => [self::BOLD],
  563. '%_' => [self::BOLD],
  564. ];
  565. if ($colored) {
  566. $string = str_replace('%%', '% ', $string);
  567. foreach ($conversions as $key => $value) {
  568. $string = str_replace(
  569. $key,
  570. static::ansiFormatCode($value),
  571. $string
  572. );
  573. }
  574. $string = str_replace('% ', '%', $string);
  575. } else {
  576. $string = preg_replace('/%((%)|.)/', '$2', $string);
  577. }
  578. return $string;
  579. }
  580. /**
  581. * Escapes % so they don't get interpreted as color codes when
  582. * the string is parsed by [[renderColoredString]].
  583. *
  584. * @param string $string String to escape
  585. *
  586. * @return string
  587. */
  588. public static function escape($string)
  589. {
  590. // TODO rework/refactor according to https://github.com/yiisoft/yii2/issues/746
  591. return str_replace('%', '%%', $string);
  592. }
  593. /**
  594. * Returns true if the stream supports colorization. ANSI colors are disabled if not supported by the stream.
  595. *
  596. * - windows without ansicon
  597. * - not tty consoles
  598. *
  599. * @param mixed $stream
  600. * @return bool true if the stream supports ANSI colors, otherwise false.
  601. */
  602. public static function streamSupportsAnsiColors($stream)
  603. {
  604. return DIRECTORY_SEPARATOR === '\\'
  605. ? getenv('ANSICON') !== false || getenv('ConEmuANSI') === 'ON'
  606. : function_exists('posix_isatty') && @posix_isatty($stream);
  607. }
  608. /**
  609. * Returns true if the console is running on windows.
  610. * @return bool
  611. */
  612. public static function isRunningOnWindows()
  613. {
  614. return DIRECTORY_SEPARATOR === '\\';
  615. }
  616. /**
  617. * Returns terminal screen size.
  618. *
  619. * Usage:
  620. *
  621. * ```php
  622. * list($width, $height) = ConsoleHelper::getScreenSize();
  623. * ```
  624. *
  625. * @param bool $refresh whether to force checking and not re-use cached size value.
  626. * This is useful to detect changing window size while the application is running but may
  627. * not get up to date values on every terminal.
  628. * @return array|bool An array of ($width, $height) or false when it was not able to determine size.
  629. */
  630. public static function getScreenSize($refresh = false)
  631. {
  632. static $size;
  633. if ($size !== null && !$refresh) {
  634. return $size;
  635. }
  636. if (static::isRunningOnWindows()) {
  637. $output = [];
  638. exec('mode con', $output);
  639. if (isset($output[1]) && strpos($output[1], 'CON') !== false) {
  640. return $size = [(int) preg_replace('~\D~', '', $output[4]), (int) preg_replace('~\D~', '', $output[3])];
  641. }
  642. } else {
  643. // try stty if available
  644. $stty = [];
  645. if (exec('stty -a 2>&1', $stty)) {
  646. $stty = implode(' ', $stty);
  647. // Linux stty output
  648. if (preg_match('/rows\s+(\d+);\s*columns\s+(\d+);/mi', $stty, $matches)) {
  649. return $size = [(int) $matches[2], (int) $matches[1]];
  650. }
  651. // MacOS stty output
  652. if (preg_match('/(\d+)\s+rows;\s*(\d+)\s+columns;/mi', $stty, $matches)) {
  653. return $size = [(int) $matches[2], (int) $matches[1]];
  654. }
  655. }
  656. // fallback to tput, which may not be updated on terminal resize
  657. if (($width = (int) exec('tput cols 2>&1')) > 0 && ($height = (int) exec('tput lines 2>&1')) > 0) {
  658. return $size = [$width, $height];
  659. }
  660. // fallback to ENV variables, which may not be updated on terminal resize
  661. if (($width = (int) getenv('COLUMNS')) > 0 && ($height = (int) getenv('LINES')) > 0) {
  662. return $size = [$width, $height];
  663. }
  664. }
  665. return $size = false;
  666. }
  667. /**
  668. * Word wrap text with indentation to fit the screen size.
  669. *
  670. * If screen size could not be detected, or the indentation is greater than the screen size, the text will not be wrapped.
  671. *
  672. * The first line will **not** be indented, so `Console::wrapText("Lorem ipsum dolor sit amet.", 4)` will result in the
  673. * following output, given the screen width is 16 characters:
  674. *
  675. * ```
  676. * Lorem ipsum
  677. * dolor sit
  678. * amet.
  679. * ```
  680. *
  681. * @param string $text the text to be wrapped
  682. * @param int $indent number of spaces to use for indentation.
  683. * @param bool $refresh whether to force refresh of screen size.
  684. * This will be passed to [[getScreenSize()]].
  685. * @return string the wrapped text.
  686. * @since 2.0.4
  687. */
  688. public static function wrapText($text, $indent = 0, $refresh = false)
  689. {
  690. $size = static::getScreenSize($refresh);
  691. if ($size === false || $size[0] <= $indent) {
  692. return $text;
  693. }
  694. $pad = str_repeat(' ', $indent);
  695. $lines = explode("\n", wordwrap($text, $size[0] - $indent, "\n"));
  696. $first = true;
  697. foreach ($lines as $i => $line) {
  698. if ($first) {
  699. $first = false;
  700. continue;
  701. }
  702. $lines[$i] = $pad . $line;
  703. }
  704. return implode("\n", $lines);
  705. }
  706. /**
  707. * Gets input from STDIN and returns a string right-trimmed for EOLs.
  708. *
  709. * @param bool $raw If set to true, returns the raw string without trimming
  710. * @return string the string read from stdin
  711. */
  712. public static function stdin($raw = false)
  713. {
  714. return $raw ? fgets(\STDIN) : rtrim(fgets(\STDIN), PHP_EOL);
  715. }
  716. /**
  717. * Prints a string to STDOUT.
  718. *
  719. * @param string $string the string to print
  720. * @return int|bool Number of bytes printed or false on error
  721. */
  722. public static function stdout($string)
  723. {
  724. return fwrite(\STDOUT, $string);
  725. }
  726. /**
  727. * Prints a string to STDERR.
  728. *
  729. * @param string $string the string to print
  730. * @return int|bool Number of bytes printed or false on error
  731. */
  732. public static function stderr($string)
  733. {
  734. return fwrite(\STDERR, $string);
  735. }
  736. /**
  737. * Asks the user for input. Ends when the user types a carriage return (PHP_EOL). Optionally, It also provides a
  738. * prompt.
  739. *
  740. * @param string $prompt the prompt to display before waiting for input (optional)
  741. * @return string the user's input
  742. */
  743. public static function input($prompt = null)
  744. {
  745. if (isset($prompt)) {
  746. static::stdout($prompt);
  747. }
  748. return static::stdin();
  749. }
  750. /**
  751. * Prints text to STDOUT appended with a carriage return (PHP_EOL).
  752. *
  753. * @param string $string the text to print
  754. * @return int|bool number of bytes printed or false on error.
  755. */
  756. public static function output($string = null)
  757. {
  758. return static::stdout($string . PHP_EOL);
  759. }
  760. /**
  761. * Prints text to STDERR appended with a carriage return (PHP_EOL).
  762. *
  763. * @param string $string the text to print
  764. * @return int|bool number of bytes printed or false on error.
  765. */
  766. public static function error($string = null)
  767. {
  768. return static::stderr($string . PHP_EOL);
  769. }
  770. /**
  771. * Prompts the user for input and validates it.
  772. *
  773. * @param string $text prompt string
  774. * @param array $options the options to validate the input:
  775. *
  776. * - `required`: whether it is required or not
  777. * - `default`: default value if no input is inserted by the user
  778. * - `pattern`: regular expression pattern to validate user input
  779. * - `validator`: a callable function to validate input. The function must accept two parameters:
  780. * - `input`: the user input to validate
  781. * - `error`: the error value passed by reference if validation failed.
  782. *
  783. * @return string the user input
  784. */
  785. public static function prompt($text, $options = [])
  786. {
  787. $options = ArrayHelper::merge(
  788. [
  789. 'required' => false,
  790. 'default' => null,
  791. 'pattern' => null,
  792. 'validator' => null,
  793. 'error' => 'Invalid input.',
  794. ],
  795. $options
  796. );
  797. $error = null;
  798. top:
  799. $input = $options['default']
  800. ? static::input("$text [" . $options['default'] . '] ')
  801. : static::input("$text ");
  802. if ($input === '') {
  803. if (isset($options['default'])) {
  804. $input = $options['default'];
  805. } elseif ($options['required']) {
  806. static::output($options['error']);
  807. goto top;
  808. }
  809. } elseif ($options['pattern'] && !preg_match($options['pattern'], $input)) {
  810. static::output($options['error']);
  811. goto top;
  812. } elseif ($options['validator'] &&
  813. !call_user_func_array($options['validator'], [$input, &$error])
  814. ) {
  815. static::output(isset($error) ? $error : $options['error']);
  816. goto top;
  817. }
  818. return $input;
  819. }
  820. /**
  821. * Asks user to confirm by typing y or n.
  822. *
  823. * A typical usage looks like the following:
  824. *
  825. * ```php
  826. * if (Console::confirm("Are you sure?")) {
  827. * echo "user typed yes\n";
  828. * } else {
  829. * echo "user typed no\n";
  830. * }
  831. * ```
  832. *
  833. * @param string $message to print out before waiting for user input
  834. * @param bool $default this value is returned if no selection is made.
  835. * @return bool whether user confirmed
  836. */
  837. public static function confirm($message, $default = false)
  838. {
  839. while (true) {
  840. static::stdout($message . ' (yes|no) [' . ($default ? 'yes' : 'no') . ']:');
  841. $input = trim(static::stdin());
  842. if (empty($input)) {
  843. return $default;
  844. }
  845. if (!strcasecmp($input, 'y') || !strcasecmp($input, 'yes')) {
  846. return true;
  847. }
  848. if (!strcasecmp($input, 'n') || !strcasecmp($input, 'no')) {
  849. return false;
  850. }
  851. }
  852. }
  853. /**
  854. * Gives the user an option to choose from. Giving '?' as an input will show
  855. * a list of options to choose from and their explanations.
  856. *
  857. * @param string $prompt the prompt message
  858. * @param array $options Key-value array of options to choose from. Key is what is inputed and used, value is
  859. * what's displayed to end user by help command.
  860. *
  861. * @return string An option character the user chose
  862. */
  863. public static function select($prompt, $options = [])
  864. {
  865. top:
  866. static::stdout("$prompt [" . implode(',', array_keys($options)) . ',?]: ');
  867. $input = static::stdin();
  868. if ($input === '?') {
  869. foreach ($options as $key => $value) {
  870. static::output(" $key - $value");
  871. }
  872. static::output(' ? - Show help');
  873. goto top;
  874. } elseif (!array_key_exists($input, $options)) {
  875. goto top;
  876. }
  877. return $input;
  878. }
  879. private static $_progressStart;
  880. private static $_progressWidth;
  881. private static $_progressPrefix;
  882. private static $_progressEta;
  883. private static $_progressEtaLastDone = 0;
  884. private static $_progressEtaLastUpdate;
  885. /**
  886. * Starts display of a progress bar on screen.
  887. *
  888. * This bar will be updated by [[updateProgress()]] and may be ended by [[endProgress()]].
  889. *
  890. * The following example shows a simple usage of a progress bar:
  891. *
  892. * ```php
  893. * Console::startProgress(0, 1000);
  894. * for ($n = 1; $n <= 1000; $n++) {
  895. * usleep(1000);
  896. * Console::updateProgress($n, 1000);
  897. * }
  898. * Console::endProgress();
  899. * ```
  900. *
  901. * Git clone like progress (showing only status information):
  902. *
  903. * ```php
  904. * Console::startProgress(0, 1000, 'Counting objects: ', false);
  905. * for ($n = 1; $n <= 1000; $n++) {
  906. * usleep(1000);
  907. * Console::updateProgress($n, 1000);
  908. * }
  909. * Console::endProgress("done." . PHP_EOL);
  910. * ```
  911. *
  912. * @param int $done the number of items that are completed.
  913. * @param int $total the total value of items that are to be done.
  914. * @param string $prefix an optional string to display before the progress bar.
  915. * Default to empty string which results in no prefix to be displayed.
  916. * @param int|bool $width optional width of the progressbar. This can be an integer representing
  917. * the number of characters to display for the progress bar or a float between 0 and 1 representing the
  918. * percentage of screen with the progress bar may take. It can also be set to false to disable the
  919. * bar and only show progress information like percent, number of items and ETA.
  920. * If not set, the bar will be as wide as the screen. Screen size will be detected using [[getScreenSize()]].
  921. * @see startProgress
  922. * @see updateProgress
  923. * @see endProgress
  924. */
  925. public static function startProgress($done, $total, $prefix = '', $width = null)
  926. {
  927. self::$_progressStart = time();
  928. self::$_progressWidth = $width;
  929. self::$_progressPrefix = $prefix;
  930. self::$_progressEta = null;
  931. self::$_progressEtaLastDone = 0;
  932. self::$_progressEtaLastUpdate = time();
  933. static::updateProgress($done, $total);
  934. }
  935. /**
  936. * Updates a progress bar that has been started by [[startProgress()]].
  937. *
  938. * @param int $done the number of items that are completed.
  939. * @param int $total the total value of items that are to be done.
  940. * @param string $prefix an optional string to display before the progress bar.
  941. * Defaults to null meaning the prefix specified by [[startProgress()]] will be used.
  942. * If prefix is specified it will update the prefix that will be used by later calls.
  943. * @see startProgress
  944. * @see endProgress
  945. */
  946. public static function updateProgress($done, $total, $prefix = null)
  947. {
  948. if ($prefix === null) {
  949. $prefix = self::$_progressPrefix;
  950. } else {
  951. self::$_progressPrefix = $prefix;
  952. }
  953. $width = static::getProgressbarWidth($prefix);
  954. $percent = ($total == 0) ? 1 : $done / $total;
  955. $info = sprintf('%d%% (%d/%d)', $percent * 100, $done, $total);
  956. self::setETA($done, $total);
  957. $info .= self::$_progressEta === null ? ' ETA: n/a' : sprintf(' ETA: %d sec.', self::$_progressEta);
  958. // Number extra characters outputted. These are opening [, closing ], and space before info
  959. // Since Windows uses \r\n\ for line endings, there's one more in the case
  960. $extraChars = static::isRunningOnWindows() ? 4 : 3;
  961. $width -= $extraChars + static::ansiStrlen($info);
  962. // skipping progress bar on very small display or if forced to skip
  963. if ($width < 5) {
  964. static::stdout("\r$prefix$info ");
  965. } else {
  966. if ($percent < 0) {
  967. $percent = 0;
  968. } elseif ($percent > 1) {
  969. $percent = 1;
  970. }
  971. $bar = floor($percent * $width);
  972. $status = str_repeat('=', $bar);
  973. if ($bar < $width) {
  974. $status .= '>';
  975. $status .= str_repeat(' ', $width - $bar - 1);
  976. }
  977. static::stdout("\r$prefix" . "[$status] $info");
  978. }
  979. flush();
  980. }
  981. /**
  982. * Return width of the progressbar
  983. * @param string $prefix an optional string to display before the progress bar.
  984. * @see updateProgress
  985. * @return int screen width
  986. * @since 2.0.14
  987. */
  988. private static function getProgressbarWidth($prefix)
  989. {
  990. $width = self::$_progressWidth;
  991. if ($width === false) {
  992. return 0;
  993. }
  994. $screenSize = static::getScreenSize(true);
  995. if ($screenSize === false && $width < 1) {
  996. return 0;
  997. }
  998. if ($width === null) {
  999. $width = $screenSize[0];
  1000. } elseif ($width > 0 && $width < 1) {
  1001. $width = floor($screenSize[0] * $width);
  1002. }
  1003. $width -= static::ansiStrlen($prefix);
  1004. return $width;
  1005. }
  1006. /**
  1007. * Calculate $_progressEta, $_progressEtaLastUpdate and $_progressEtaLastDone
  1008. * @param int $done the number of items that are completed.
  1009. * @param int $total the total value of items that are to be done.
  1010. * @see updateProgress
  1011. * @since 2.0.14
  1012. */
  1013. private static function setETA($done, $total)
  1014. {
  1015. if ($done > $total || $done == 0) {
  1016. self::$_progressEta = null;
  1017. self::$_progressEtaLastUpdate = time();
  1018. return;
  1019. }
  1020. if ($done < $total && (time() - self::$_progressEtaLastUpdate > 1 && $done > self::$_progressEtaLastDone)) {
  1021. $rate = (time() - (self::$_progressEtaLastUpdate ?: self::$_progressStart)) / ($done - self::$_progressEtaLastDone);
  1022. self::$_progressEta = $rate * ($total - $done);
  1023. self::$_progressEtaLastUpdate = time();
  1024. self::$_progressEtaLastDone = $done;
  1025. }
  1026. }
  1027. /**
  1028. * Ends a progress bar that has been started by [[startProgress()]].
  1029. *
  1030. * @param string|bool $remove This can be `false` to leave the progress bar on screen and just print a newline.
  1031. * If set to `true`, the line of the progress bar will be cleared. This may also be a string to be displayed instead
  1032. * of the progress bar.
  1033. * @param bool $keepPrefix whether to keep the prefix that has been specified for the progressbar when progressbar
  1034. * gets removed. Defaults to true.
  1035. * @see startProgress
  1036. * @see updateProgress
  1037. */
  1038. public static function endProgress($remove = false, $keepPrefix = true)
  1039. {
  1040. if ($remove === false) {
  1041. static::stdout(PHP_EOL);
  1042. } else {
  1043. if (static::streamSupportsAnsiColors(STDOUT)) {
  1044. static::clearLine();
  1045. }
  1046. static::stdout("\r" . ($keepPrefix ? self::$_progressPrefix : '') . (is_string($remove) ? $remove : ''));
  1047. }
  1048. flush();
  1049. self::$_progressStart = null;
  1050. self::$_progressWidth = null;
  1051. self::$_progressPrefix = '';
  1052. self::$_progressEta = null;
  1053. self::$_progressEtaLastDone = 0;
  1054. self::$_progressEtaLastUpdate = null;
  1055. }
  1056. /**
  1057. * Generates a summary of the validation errors.
  1058. * @param Model|Model[] $models the model(s) whose validation errors are to be displayed.
  1059. * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
  1060. *
  1061. * - showAllErrors: boolean, if set to true every error message for each attribute will be shown otherwise
  1062. * only the first error message for each attribute will be shown. Defaults to `false`.
  1063. *
  1064. * @return string the generated error summary
  1065. * @since 2.0.14
  1066. */
  1067. public static function errorSummary($models, $options = [])
  1068. {
  1069. $showAllErrors = ArrayHelper::remove($options, 'showAllErrors', false);
  1070. $lines = self::collectErrors($models, $showAllErrors);
  1071. return implode(PHP_EOL, $lines);
  1072. }
  1073. /**
  1074. * Return array of the validation errors
  1075. * @param Model|Model[] $models the model(s) whose validation errors are to be displayed.
  1076. * @param $showAllErrors boolean, if set to true every error message for each attribute will be shown otherwise
  1077. * only the first error message for each attribute will be shown.
  1078. * @return array of the validation errors
  1079. * @since 2.0.14
  1080. */
  1081. private static function collectErrors($models, $showAllErrors)
  1082. {
  1083. $lines = [];
  1084. if (!is_array($models)) {
  1085. $models = [$models];
  1086. }
  1087. foreach ($models as $model) {
  1088. $lines = array_unique(array_merge($lines, $model->getErrorSummary($showAllErrors)));
  1089. }
  1090. return $lines;
  1091. }
  1092. }