BaseConsole.php 27.1 KB
Newer Older
Qiang Xue committed
1 2 3 4 5 6 7
<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

8
namespace yii\helpers;
Qiang Xue committed
9 10

/**
11
 * BaseConsole provides concrete implementation for [[Console]].
12
 *
13
 * Do not use BaseConsole. Use [[Console]] instead.
14
 *
Qiang Xue committed
15 16 17
 * @author Carsten Brandt <mail@cebe.cc>
 * @since 2.0
 */
18
class BaseConsole
Qiang Xue committed
19
{
Carsten Brandt committed
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
	const FG_BLACK  = 30;
	const FG_RED    = 31;
	const FG_GREEN  = 32;
	const FG_YELLOW = 33;
	const FG_BLUE   = 34;
	const FG_PURPLE = 35;
	const FG_CYAN   = 36;
	const FG_GREY   = 37;

	const BG_BLACK  = 40;
	const BG_RED    = 41;
	const BG_GREEN  = 42;
	const BG_YELLOW = 43;
	const BG_BLUE   = 44;
	const BG_PURPLE = 45;
	const BG_CYAN   = 46;
	const BG_GREY   = 47;

38
	const RESET       = 0;
Carsten Brandt committed
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
	const NORMAL      = 0;
	const BOLD        = 1;
	const ITALIC      = 3;
	const UNDERLINE   = 4;
	const BLINK       = 5;
	const NEGATIVE    = 7;
	const CONCEALED   = 8;
	const CROSSED_OUT = 9;
	const FRAMED      = 51;
	const ENCIRCLED   = 52;
	const OVERLINED   = 53;

	/**
	 * Moves the terminal cursor up by sending ANSI control code CUU to the terminal.
	 * If the cursor is already at the edge of the screen, this has no effect.
	 * @param integer $rows number of rows the cursor should be moved up
	 */
	public static function moveCursorUp($rows = 1)
	{
		echo "\033[" . (int)$rows . 'A';
	}

	/**
	 * Moves the terminal cursor down by sending ANSI control code CUD to the terminal.
	 * If the cursor is already at the edge of the screen, this has no effect.
	 * @param integer $rows number of rows the cursor should be moved down
	 */
	public static function moveCursorDown($rows = 1)
	{
		echo "\033[" . (int)$rows . 'B';
	}

	/**
	 * Moves the terminal cursor forward by sending ANSI control code CUF to the terminal.
	 * If the cursor is already at the edge of the screen, this has no effect.
	 * @param integer $steps number of steps the cursor should be moved forward
	 */
	public static function moveCursorForward($steps = 1)
	{
		echo "\033[" . (int)$steps . 'C';
	}

	/**
	 * Moves the terminal cursor backward by sending ANSI control code CUB to the terminal.
	 * If the cursor is already at the edge of the screen, this has no effect.
	 * @param integer $steps number of steps the cursor should be moved backward
	 */
	public static function moveCursorBackward($steps = 1)
	{
		echo "\033[" . (int)$steps . 'D';
	}

	/**
	 * Moves the terminal cursor to the beginning of the next line by sending ANSI control code CNL to the terminal.
	 * @param integer $lines number of lines the cursor should be moved down
	 */
	public static function moveCursorNextLine($lines = 1)
	{
		echo "\033[" . (int)$lines . 'E';
	}

	/**
	 * Moves the terminal cursor to the beginning of the previous line by sending ANSI control code CPL to the terminal.
	 * @param integer $lines number of lines the cursor should be moved up
	 */
	public static function moveCursorPrevLine($lines = 1)
	{
		echo "\033[" . (int)$lines . 'F';
	}

	/**
	 * Moves the cursor to an absolute position given as column and row by sending ANSI control code CUP or CHA to the terminal.
	 * @param integer $column 1-based column number, 1 is the left edge of the screen.
	 * @param integer|null $row 1-based row number, 1 is the top edge of the screen. if not set, will move cursor only in current line.
	 */
	public static function moveCursorTo($column, $row = null)
	{
		if ($row === null) {
			echo "\033[" . (int)$column . 'G';
		} else {
			echo "\033[" . (int)$row . ';' . (int)$column . 'H';
		}
	}

	/**
	 * Scrolls whole page up by sending ANSI control code SU to the terminal.
	 * New lines are added at the bottom. This is not supported by ANSI.SYS used in windows.
	 * @param int $lines number of lines to scroll up
	 */
	public static function scrollUp($lines = 1)
	{
		echo "\033[" . (int)$lines . "S";
	}

	/**
	 * Scrolls whole page down by sending ANSI control code SD to the terminal.
	 * New lines are added at the top. This is not supported by ANSI.SYS used in windows.
	 * @param int $lines number of lines to scroll down
	 */
	public static function scrollDown($lines = 1)
	{
		echo "\033[" . (int)$lines . "T";
	}

	/**
	 * Saves the current cursor position by sending ANSI control code SCP to the terminal.
Qiang Xue committed
145
	 * Position can then be restored with [[restoreCursorPosition()]].
Carsten Brandt committed
146 147 148 149 150 151 152
	 */
	public static function saveCursorPosition()
	{
		echo "\033[s";
	}

	/**
Qiang Xue committed
153
	 * Restores the cursor position saved with [[saveCursorPosition()]] by sending ANSI control code RCP to the terminal.
Carsten Brandt committed
154 155 156 157 158 159 160 161
	 */
	public static function restoreCursorPosition()
	{
		echo "\033[u";
	}

	/**
	 * Hides the cursor by sending ANSI DECTCEM code ?25l to the terminal.
Qiang Xue committed
162
	 * Use [[showCursor()]] to bring it back.
Carsten Brandt committed
163 164 165 166 167 168 169 170
	 * Do not forget to show cursor when your application exits. Cursor might stay hidden in terminal after exit.
	 */
	public static function hideCursor()
	{
		echo "\033[?25l";
	}

	/**
Qiang Xue committed
171
	 * Will show a cursor again when it has been hidden by [[hideCursor()]]  by sending ANSI DECTCEM code ?25h to the terminal.
Carsten Brandt committed
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
	 */
	public static function showCursor()
	{
		echo "\033[?25h";
	}

	/**
	 * Clears entire screen content by sending ANSI control code ED with argument 2 to the terminal.
	 * Cursor position will not be changed.
	 * **Note:** ANSI.SYS implementation used in windows will reset cursor position to upper left corner of the screen.
	 */
	public static function clearScreen()
	{
		echo "\033[2J";
	}

	/**
	 * Clears text from cursor to the beginning of the screen by sending ANSI control code ED with argument 1 to the terminal.
	 * Cursor position will not be changed.
	 */
	public static function clearScreenBeforeCursor()
	{
		echo "\033[1J";
	}

	/**
	 * Clears text from cursor to the end of the screen by sending ANSI control code ED with argument 0 to the terminal.
	 * Cursor position will not be changed.
	 */
	public static function clearScreenAfterCursor()
	{
		echo "\033[0J";
	}

	/**
	 * Clears the line, the cursor is currently on by sending ANSI control code EL with argument 2 to the terminal.
	 * Cursor position will not be changed.
	 */
	public static function clearLine()
	{
		echo "\033[2K";
	}

	/**
	 * Clears text from cursor position to the beginning of the line by sending ANSI control code EL with argument 1 to the terminal.
	 * Cursor position will not be changed.
	 */
	public static function clearLineBeforeCursor()
	{
		echo "\033[1K";
	}

	/**
	 * Clears text from cursor position to the end of the line by sending ANSI control code EL with argument 0 to the terminal.
	 * Cursor position will not be changed.
	 */
	public static function clearLineAfterCursor()
	{
		echo "\033[0K";
	}

	/**
234
	 * Returns the ANSI format code.
Carsten Brandt committed
235
	 *
236 237 238 239
	 * @param array $format An array containing formatting values.
	 * You can pass any of the FG_*, BG_* and TEXT_* constants
	 * and also [[xtermFgColor]] and [[xtermBgColor]] to specify a format.
	 * @return string The ANSI format code according to the given formatting constants.
Carsten Brandt committed
240
	 */
241
	public static function ansiFormatCode($format)
Carsten Brandt committed
242
	{
243
		return "\033[" . implode(';', $format) . 'm';
Carsten Brandt committed
244 245
	}

246
	/**
247
	 * Echoes an ANSI format code that affects the formatting of any text that is printed afterwards.
248
	 *
249 250 251 252
	 * @param array $format An array containing formatting values.
	 * You can pass any of the FG_*, BG_* and TEXT_* constants
	 * and also [[xtermFgColor]] and [[xtermBgColor]] to specify a format.
	 * @see ansiFormatCode()
253
	 * @see ansiFormatEnd()
254
	 */
255
	public static function beginAnsiFormat($format)
256
	{
257
		echo "\033[" . implode(';', $format) . 'm';
258 259 260
	}

	/**
261
	 * Resets any ANSI format set by previous method [[ansiFormatBegin()]]
262 263
	 * Any output after this will have default text format.
	 * This is equal to calling
264
	 *
265
	 * ```php
Alexander Makarov committed
266
	 * echo Console::ansiFormatCode([Console::RESET])
267
	 * ```
268
	 */
269
	public static function endAnsiFormat()
270
	{
271
		echo "\033[0m";
272 273
	}

Carsten Brandt committed
274 275 276 277
	/**
	 * Will return a string formatted with the given ANSI style
	 *
	 * @param string $string the string to be formatted
278 279 280
	 * @param array $format An array containing formatting values.
	 * You can pass any of the FG_*, BG_* and TEXT_* constants
	 * and also [[xtermFgColor]] and [[xtermBgColor]] to specify a format.
Carsten Brandt committed
281 282
	 * @return string
	 */
Alexander Makarov committed
283
	public static function ansiFormat($string, $format = [])
Carsten Brandt committed
284
	{
285
		$code = implode(';', $format);
Carsten Brandt committed
286 287 288
		return "\033[0m" . ($code !== '' ? "\033[" . $code . "m" : '') . $string . "\033[0m";
	}

289 290
	/**
	 * Returns the ansi format code for xterm foreground color.
291
	 * You can pass the return value of this to one of the formatting methods:
292 293 294 295 296 297 298
	 * [[ansiFormat]], [[ansiFormatCode]], [[beginAnsiFormat]]
	 *
	 * @param integer $colorCode xterm color code
	 * @return string
	 * @see http://en.wikipedia.org/wiki/Talk:ANSI_escape_code#xterm-256colors
	 */
	public static function xtermFgColor($colorCode)
Carsten Brandt committed
299
	{
300
		return '38;5;' . $colorCode;
Carsten Brandt committed
301 302
	}

303
	/**
304 305
	 * Returns the ansi format code for xterm background color.
	 * You can pass the return value of this to one of the formatting methods:
306 307 308 309 310 311 312
	 * [[ansiFormat]], [[ansiFormatCode]], [[beginAnsiFormat]]
	 *
	 * @param integer $colorCode xterm color code
	 * @return string
	 * @see http://en.wikipedia.org/wiki/Talk:ANSI_escape_code#xterm-256colors
	 */
	public static function xtermBgColor($colorCode)
Carsten Brandt committed
313
	{
314
		return '48;5;' . $colorCode;
Carsten Brandt committed
315 316 317 318 319 320 321 322
	}

	/**
	 * Strips ANSI control codes from a string
	 *
	 * @param string $string String to strip
	 * @return string
	 */
323
	public static function stripAnsiFormat($string)
Carsten Brandt committed
324
	{
325
		return preg_replace('/\033\[[\d;?]*\w/', '', $string);
Carsten Brandt committed
326 327
	}

328 329 330 331 332 333
	/**
	 * Converts an ANSI formatted string to HTML
	 * @param $string
	 * @return mixed
	 */
	// TODO rework/refactor according to https://github.com/yiisoft/yii2/issues/746
Carsten Brandt committed
334 335 336 337 338 339
	public static function ansiToHtml($string)
	{
		$tags = 0;
		return preg_replace_callback(
			'/\033\[[\d;]+m/',
			function ($ansi) use (&$tags) {
Alexander Makarov committed
340
				$styleA = [];
Carsten Brandt committed
341 342
				foreach (explode(';', $ansi) as $controlCode) {
					switch ($controlCode) {
343
						case self::FG_BLACK:
Alexander Makarov committed
344
							$style = ['color' => '#000000'];
Carsten Brandt committed
345
							break;
346
						case self::FG_BLUE:
Alexander Makarov committed
347
							$style = ['color' => '#000078'];
Carsten Brandt committed
348
							break;
349
						case self::FG_CYAN:
Alexander Makarov committed
350
							$style = ['color' => '#007878'];
Carsten Brandt committed
351
							break;
352
						case self::FG_GREEN:
Alexander Makarov committed
353
							$style = ['color' => '#007800'];
Carsten Brandt committed
354
							break;
355
						case self::FG_GREY:
Alexander Makarov committed
356
							$style = ['color' => '#787878'];
Carsten Brandt committed
357
							break;
358
						case self::FG_PURPLE:
Alexander Makarov committed
359
							$style = ['color' => '#780078'];
Carsten Brandt committed
360
							break;
361
						case self::FG_RED:
Alexander Makarov committed
362
							$style = ['color' => '#780000'];
Carsten Brandt committed
363
							break;
364
						case self::FG_YELLOW:
Alexander Makarov committed
365
							$style = ['color' => '#787800'];
Carsten Brandt committed
366
							break;
367
						case self::BG_BLACK:
Alexander Makarov committed
368
							$style = ['background-color' => '#000000'];
Carsten Brandt committed
369
							break;
370
						case self::BG_BLUE:
Alexander Makarov committed
371
							$style = ['background-color' => '#000078'];
Carsten Brandt committed
372
							break;
373
						case self::BG_CYAN:
Alexander Makarov committed
374
							$style = ['background-color' => '#007878'];
Carsten Brandt committed
375
							break;
376
						case self::BG_GREEN:
Alexander Makarov committed
377
							$style = ['background-color' => '#007800'];
Carsten Brandt committed
378
							break;
379
						case self::BG_GREY:
Alexander Makarov committed
380
							$style = ['background-color' => '#787878'];
Carsten Brandt committed
381
							break;
382
						case self::BG_PURPLE:
Alexander Makarov committed
383
							$style = ['background-color' => '#780078'];
Carsten Brandt committed
384
							break;
385
						case self::BG_RED:
Alexander Makarov committed
386
							$style = ['background-color' => '#780000'];
Carsten Brandt committed
387
							break;
388
						case self::BG_YELLOW:
Alexander Makarov committed
389
							$style = ['background-color' => '#787800'];
Carsten Brandt committed
390
							break;
391
						case self::BOLD:
Alexander Makarov committed
392
							$style = ['font-weight' => 'bold'];
Carsten Brandt committed
393
							break;
394
						case self::ITALIC:
Alexander Makarov committed
395
							$style = ['font-style' => 'italic'];
Carsten Brandt committed
396
							break;
397
						case self::UNDERLINE:
Alexander Makarov committed
398
							$style = ['text-decoration' => ['underline']];
Carsten Brandt committed
399
							break;
400
						case self::OVERLINED:
Alexander Makarov committed
401
							$style = ['text-decoration' => ['overline']];
Carsten Brandt committed
402
							break;
403
						case self::CROSSED_OUT:
Alexander Makarov committed
404
							$style = ['text-decoration' => ['line-through']];
Carsten Brandt committed
405
							break;
406
						case self::BLINK:
Alexander Makarov committed
407
							$style = ['text-decoration' => ['blink']];
Carsten Brandt committed
408
							break;
409 410 411 412
						case self::NEGATIVE: // ???
						case self::CONCEALED:
						case self::ENCIRCLED:
						case self::FRAMED:
Carsten Brandt committed
413 414 415 416 417 418 419 420 421 422 423 424
							// TODO allow resetting codes
							break;
						case 0: // ansi reset
							$return = '';
							for ($n = $tags; $tags > 0; $tags--) {
								$return .= '</span>';
							}
							return $return;
					}

					$styleA = ArrayHelper::merge($styleA, $style);
				}
Alexander Makarov committed
425
				$styleString[] = [];
Carsten Brandt committed
426 427 428 429 430 431 432 433 434 435 436 437 438
				foreach ($styleA as $name => $content) {
					if ($name === 'text-decoration') {
						$content = implode(' ', $content);
					}
					$styleString[] = $name . ':' . $content;
				}
				$tags++;
				return '<span' . (!empty($styleString) ? 'style="' . implode(';', $styleString) : '') . '>';
			},
			$string
		);
	}

439
	// TODO rework/refactor according to https://github.com/yiisoft/yii2/issues/746
440
	public function markdownToAnsi()
Carsten Brandt committed
441
	{
442
		// TODO implement
Carsten Brandt committed
443 444 445
	}

	/**
446
	 * Converts a string to ansi formatted by replacing patterns like %y (for yellow) with ansi control codes
Carsten Brandt committed
447
	 *
448 449
	 * Uses almost the same syntax as https://github.com/pear/Console_Color2/blob/master/Console/Color2.php
	 * The conversion table is: ('bold' meaning 'light' on some
Carsten Brandt committed
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
	 * terminals). It's almost the same conversion table irssi uses.
	 * <pre>
	 *                  text      text            background
	 *      ------------------------------------------------
	 *      %k %K %0    black     dark grey       black
	 *      %r %R %1    red       bold red        red
	 *      %g %G %2    green     bold green      green
	 *      %y %Y %3    yellow    bold yellow     yellow
	 *      %b %B %4    blue      bold blue       blue
	 *      %m %M %5    magenta   bold magenta    magenta
	 *      %p %P       magenta (think: purple)
	 *      %c %C %6    cyan      bold cyan       cyan
	 *      %w %W %7    white     bold white      white
	 *
	 *      %F     Blinking, Flashing
	 *      %U     Underline
	 *      %8     Reverse
	 *      %_,%9  Bold
	 *
	 *      %n     Resets the color
	 *      %%     A single %
	 * </pre>
	 * First param is the string to convert, second is an optional flag if
	 * colors should be used. It defaults to true, if set to false, the
	 * colorcodes will just be removed (And %% will be transformed into %)
	 *
	 * @param string $string  String to convert
	 * @param bool   $colored Should the string be colored?
	 * @return string
	 */
480
	// TODO rework/refactor according to https://github.com/yiisoft/yii2/issues/746
Carsten Brandt committed
481 482
	public static function renderColoredString($string, $colored = true)
	{
Alexander Makarov committed
483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
		static $conversions = [
			'%y' => [self::FG_YELLOW],
			'%g' => [self::FG_GREEN],
			'%b' => [self::FG_BLUE],
			'%r' => [self::FG_RED],
			'%p' => [self::FG_PURPLE],
			'%m' => [self::FG_PURPLE],
			'%c' => [self::FG_CYAN],
			'%w' => [self::FG_GREY],
			'%k' => [self::FG_BLACK],
			'%n' => [0], // reset
			'%Y' => [self::FG_YELLOW, self::BOLD],
			'%G' => [self::FG_GREEN, self::BOLD],
			'%B' => [self::FG_BLUE, self::BOLD],
			'%R' => [self::FG_RED, self::BOLD],
			'%P' => [self::FG_PURPLE, self::BOLD],
			'%M' => [self::FG_PURPLE, self::BOLD],
			'%C' => [self::FG_CYAN, self::BOLD],
			'%W' => [self::FG_GREY, self::BOLD],
			'%K' => [self::FG_BLACK, self::BOLD],
			'%N' => [0, self::BOLD],
			'%3' => [self::BG_YELLOW],
			'%2' => [self::BG_GREEN],
			'%4' => [self::BG_BLUE],
			'%1' => [self::BG_RED],
			'%5' => [self::BG_PURPLE],
			'%6' => [self::BG_PURPLE],
			'%7' => [self::BG_CYAN],
			'%0' => [self::BG_GREY],
			'%F' => [self::BLINK],
			'%U' => [self::UNDERLINE],
			'%8' => [self::NEGATIVE],
			'%9' => [self::BOLD],
			'%_' => [self::BOLD],
		];
Carsten Brandt committed
518 519 520 521 522 523

		if ($colored) {
			$string = str_replace('%%', '% ', $string);
			foreach ($conversions as $key => $value) {
				$string = str_replace(
					$key,
524
					static::ansiFormatCode($value),
Carsten Brandt committed
525 526 527 528 529 530 531 532 533 534 535
					$string
				);
			}
			$string = str_replace('% ', '%', $string);
		} else {
			$string = preg_replace('/%((%)|.)/', '$2', $string);
		}
		return $string;
	}

	/**
536 537 538 539 540 541 542 543
	 * Escapes % so they don't get interpreted as color codes when
	 * the string is parsed by [[renderColoredString]]
	 *
	 * @param string $string String to escape
	 *
	 * @access public
	 * @return string
	 */
544
	// TODO rework/refactor according to https://github.com/yiisoft/yii2/issues/746
Carsten Brandt committed
545 546 547 548 549 550
	public static function escape($string)
	{
		return str_replace('%', '%%', $string);
	}

	/**
551
	 * Returns true if the stream supports colorization. ANSI colors are disabled if not supported by the stream.
Carsten Brandt committed
552
	 *
553
	 * - windows without ansicon
Carsten Brandt committed
554 555 556 557 558 559 560 561
	 * - not tty consoles
	 *
	 * @param mixed $stream
	 * @return bool true if the stream supports ANSI colors, otherwise false.
	 */
	public static function streamSupportsAnsiColors($stream)
	{
		return DIRECTORY_SEPARATOR == '\\'
562
			? getenv('ANSICON') !== false || getenv('ConEmuANSI') === 'ON'
Carsten Brandt committed
563 564 565 566 567 568 569 570 571
			: function_exists('posix_isatty') && @posix_isatty($stream);
	}

	/**
	 * Returns true if the console is running on windows
	 * @return bool
	 */
	public static function isRunningOnWindows()
	{
572
		return DIRECTORY_SEPARATOR == '\\';
Carsten Brandt committed
573 574 575
	}

	/**
576
	 * Usage: list($width, $height) = ConsoleHelper::getScreenSize();
Carsten Brandt committed
577
	 *
578 579 580
	 * @param bool $refresh whether to force checking and not re-use cached size value.
	 * This is useful to detect changing window size while the application is running but may
	 * not get up to date values on every terminal.
581
	 * @return array|boolean An array of ($width, $height) or false when it was not able to determine size.
Carsten Brandt committed
582
	 */
583
	public static function getScreenSize($refresh = false)
Carsten Brandt committed
584
	{
585 586 587 588 589 590
		static $size;
		if ($size !== null && !$refresh) {
			return $size;
		}

		if (static::isRunningOnWindows()) {
Alexander Makarov committed
591
			$output = [];
592
			exec('mode con', $output);
resurtm committed
593
			if (isset($output) && strpos($output[1], 'CON') !== false) {
Alexander Makarov committed
594
				return $size = [(int)preg_replace('~[^0-9]~', '', $output[3]), (int)preg_replace('~[^0-9]~', '', $output[4])];
595
			}
596 597
		} else {
			// try stty if available
Alexander Makarov committed
598
			$stty = [];
599
			if (exec('stty -a 2>&1', $stty) && preg_match('/rows\s+(\d+);\s*columns\s+(\d+);/mi', implode(' ', $stty), $matches)) {
Alexander Makarov committed
600
				return $size = [$matches[2], $matches[1]];
601 602 603 604
			}

			// fallback to tput, which may not be updated on terminal resize
			if (($width = (int) exec('tput cols 2>&1')) > 0 && ($height = (int) exec('tput lines 2>&1')) > 0) {
Alexander Makarov committed
605
				return $size = [$width, $height];
606 607 608 609
			}

			// fallback to ENV variables, which may not be updated on terminal resize
			if (($width = (int) getenv('COLUMNS')) > 0 && ($height = (int) getenv('LINES')) > 0) {
Alexander Makarov committed
610
				return $size = [$width, $height];
611 612 613 614
			}
		}

		return $size = false;
Carsten Brandt committed
615 616 617
	}

	/**
618
	 * Gets input from STDIN and returns a string right-trimmed for EOLs.
Carsten Brandt committed
619
	 *
620
	 * @param bool $raw If set to true, returns the raw string without trimming
621
	 * @return string the string read from stdin
Carsten Brandt committed
622
	 */
623
	public static function stdin($raw = false)
Carsten Brandt committed
624
	{
625
		return $raw ? fgets(STDIN) : rtrim(fgets(STDIN), PHP_EOL);
Carsten Brandt committed
626 627 628
	}

	/**
629
	 * Prints a string to STDOUT.
Carsten Brandt committed
630
	 *
631 632
	 * @param string $string the string to print
	 * @return int|boolean Number of bytes printed or false on error
Carsten Brandt committed
633
	 */
634
	public static function stdout($string)
Carsten Brandt committed
635
	{
636
		return fwrite(STDOUT, $string);
Carsten Brandt committed
637 638 639
	}

	/**
640
	 * Prints a string to STDERR.
Carsten Brandt committed
641
	 *
642 643
	 * @param string $string the string to print
	 * @return int|boolean Number of bytes printed or false on error
Carsten Brandt committed
644
	 */
645
	public static function stderr($string)
Carsten Brandt committed
646
	{
647
		return fwrite(STDERR, $string);
Carsten Brandt committed
648 649 650 651 652 653
	}

	/**
	 * Asks the user for input. Ends when the user types a carriage return (PHP_EOL). Optionally, It also provides a
	 * prompt.
	 *
654
	 * @param string $prompt the prompt to display before waiting for input (optional)
Carsten Brandt committed
655 656 657 658 659 660 661 662 663 664 665 666 667
	 * @return string the user's input
	 */
	public static function input($prompt = null)
	{
		if (isset($prompt)) {
			static::stdout($prompt);
		}
		return static::stdin();
	}

	/**
	 * Prints text to STDOUT appended with a carriage return (PHP_EOL).
	 *
668 669
	 * @param string $string the text to print
	 * @return integer|boolean number of bytes printed or false on error.
Carsten Brandt committed
670
	 */
671
	public static function output($string = null)
672
	{
673
		return static::stdout($string . PHP_EOL);
674 675 676 677 678
	}

	/**
	 * Prints text to STDERR appended with a carriage return (PHP_EOL).
	 *
679 680
	 * @param string $string the text to print
	 * @return integer|boolean number of bytes printed or false on error.
681
	 */
682
	public static function error($string = null)
Carsten Brandt committed
683
	{
684
		return static::stderr($string . PHP_EOL);
Carsten Brandt committed
685 686 687 688 689 690 691 692 693 694 695 696 697 698 699
	}

	/**
	 * Prompts the user for input and validates it
	 *
	 * @param string $text prompt string
	 * @param array $options the options to validate the input:
	 *  - required: whether it is required or not
	 *  - default: default value if no input is inserted by the user
	 *  - pattern: regular expression pattern to validate user input
	 *  - validator: a callable function to validate input. The function must accept two parameters:
	 *      - $input: the user input to validate
	 *      - $error: the error value passed by reference if validation failed.
	 * @return string the user input
	 */
Alexander Makarov committed
700
	public static function prompt($text, $options = [])
Carsten Brandt committed
701 702
	{
		$options = ArrayHelper::merge(
Alexander Makarov committed
703
			[
Carsten Brandt committed
704 705 706 707 708
				'required'  => false,
				'default'   => null,
				'pattern'   => null,
				'validator' => null,
				'error'     => 'Invalid input.',
Alexander Makarov committed
709
			],
710
			$options
Carsten Brandt committed
711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729
		);
		$error   = null;

		top:
		$input = $options['default']
			? static::input("$text [" . $options['default'] . ']: ')
			: static::input("$text: ");

		if (!strlen($input)) {
			if (isset($options['default'])) {
				$input = $options['default'];
			} elseif ($options['required']) {
				static::output($options['error']);
				goto top;
			}
		} elseif ($options['pattern'] && !preg_match($options['pattern'], $input)) {
			static::output($options['error']);
			goto top;
		} elseif ($options['validator'] &&
Alexander Makarov committed
730
			!call_user_func_array($options['validator'], [$input, &$error])
Carsten Brandt committed
731 732 733 734 735 736 737 738 739
		) {
			static::output(isset($error) ? $error : $options['error']);
			goto top;
		}

		return $input;
	}

	/**
740
	 * Asks user to confirm by typing y or n.
Carsten Brandt committed
741
	 *
742 743 744
	 * @param string $message to echo out before waiting for user input
	 * @param boolean $default this value is returned if no selection is made.
	 * @return boolean whether user confirmed
Carsten Brandt committed
745
	 */
746
	public static function confirm($message, $default = true)
Carsten Brandt committed
747
	{
748 749 750
		echo $message . ' (yes|no) [' . ($default ? 'yes' : 'no') . ']:';
		$input = trim(static::stdin());
		return empty($input) ? $default : !strncasecmp($input, 'y', 1);
Carsten Brandt committed
751 752 753 754 755 756 757 758 759 760 761
	}

	/**
	 * Gives the user an option to choose from. Giving '?' as an input will show
	 * a list of options to choose from and their explanations.
	 *
	 * @param string $prompt the prompt message
	 * @param array  $options Key-value array of options to choose from
	 *
	 * @return string An option character the user chose
	 */
Alexander Makarov committed
762
	public static function select($prompt, $options = [])
Carsten Brandt committed
763 764 765 766 767 768
	{
		top:
		static::stdout("$prompt [" . implode(',', array_keys($options)) . ",?]: ");
		$input = static::stdin();
		if ($input === '?') {
			foreach ($options as $key => $value) {
769
				static::output(" $key - $value");
Carsten Brandt committed
770
			}
771
			static::output(" ? - Show help");
Carsten Brandt committed
772 773 774 775 776 777 778
			goto top;
		} elseif (!in_array($input, array_keys($options))) {
			goto top;
		}
		return $input;
	}

779 780 781 782
	private static $_progressStart;
	private static $_progressWidth;
	private static $_progressPrefix;

Carsten Brandt committed
783
	/**
784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807
	 * Starts display of a progress bar on screen.
	 *
	 * This bar will be updated by [[updateProgress()]] and my be ended by [[endProgress()]].
	 *
	 * The following example shows a simple usage of a progress bar:
	 *
	 * ```php
	 * Console::startProgress(0, 1000);
	 * for ($n = 1; $n <= 1000; $n++) {
	 *     usleep(1000);
	 *     Console::updateProgress($n, 1000);
	 * }
	 * Console::endProgress();
	 * ```
	 *
	 * Git clone like progress (showing only status information):
	 * ```php
	 * Console::startProgress(0, 1000, 'Counting objects: ', false);
	 * for ($n = 1; $n <= 1000; $n++) {
	 *     usleep(1000);
	 *     Console::updateProgress($n, 1000);
	 * }
	 * Console::endProgress("done." . PHP_EOL);
	 * ```
Carsten Brandt committed
808
	 *
809 810 811 812 813 814 815 816 817 818 819 820
	 * @param integer $done the number of items that are completed.
	 * @param integer $total the total value of items that are to be done.
	 * @param string $prefix an optional string to display before the progress bar.
	 * Default to empty string which results in no prefix to be displayed.
	 * @param integer|boolean $width optional width of the progressbar. This can be an integer representing
	 * the number of characters to display for the progress bar or a float between 0 and 1 representing the
	 * percentage of screen with the progress bar may take. It can also be set to false to disable the
	 * bar and only show progress information like percent, number of items and ETA.
	 * If not set, the bar will be as wide as the screen. Screen size will be detected using [[getScreenSize()]].
	 * @see startProgress
	 * @see updateProgress
	 * @see endProgress
Carsten Brandt committed
821
	 */
822
	public static function startProgress($done, $total, $prefix = '', $width = null)
Carsten Brandt committed
823
	{
824 825 826
		self::$_progressStart = time();
		self::$_progressWidth = $width;
		self::$_progressPrefix = $prefix;
Carsten Brandt committed
827

828 829
		static::updateProgress($done, $total);
	}
Carsten Brandt committed
830

831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855
	/**
	 * Updates a progress bar that has been started by [[startProgress()]].
	 *
	 * @param integer $done the number of items that are completed.
	 * @param integer $total the total value of items that are to be done.
	 * @param string $prefix an optional string to display before the progress bar.
	 * Defaults to null meaning the prefix specified by [[startProgress()]] will be used.
	 * If prefix is specified it will update the prefix that will be used by later calls.
	 * @see startProgress
	 * @see endProgress
	 */
	public static function updateProgress($done, $total, $prefix = null)
	{
		$width = self::$_progressWidth;
		if ($width === false) {
			$width = 0;
		} else {
			$screenSize = static::getScreenSize(true);
			if ($screenSize === false && $width < 1) {
				$width = 0;
			} elseif ($width === null) {
				$width = $screenSize[0];
			} elseif ($width > 0 && $width < 1) {
				$width = floor($screenSize[0] * $width);
			}
Carsten Brandt committed
856
		}
857 858
		if ($prefix === null) {
			$prefix = self::$_progressPrefix;
Carsten Brandt committed
859
		} else {
860
			self::$_progressPrefix = $prefix;
Carsten Brandt committed
861
		}
862
		$width -= mb_strlen($prefix);
Carsten Brandt committed
863

864
		$percent = ($total == 0) ? 1 : $done / $total;
865
		$info = sprintf("%d%% (%d/%d)", $percent * 100, $done, $total);
Carsten Brandt committed
866

867 868 869 870 871 872
		if ($done > $total || $done == 0) {
			$info .= ' ETA: n/a';
		} elseif ($done < $total) {
			$rate = (time() - self::$_progressStart) / $done;
			$info .= sprintf(' ETA: %d sec.', $rate * ($total - $done));
		}
Carsten Brandt committed
873

874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891
		$width -= 3 + mb_strlen($info);
		// skipping progress bar on very small display or if forced to skip
		if ($width < 5) {
			static::stdout("\r$prefix$info   ");
		} else {
			if ($percent < 0) {
				$percent = 0;
			} elseif ($percent > 1) {
				$percent = 1;
			}
			$bar = floor($percent * $width);
			$status = str_repeat("=", $bar);
			if ($bar < $width) {
				$status .= ">";
				$status .= str_repeat(" ", $width - $bar - 1);
			}
			static::stdout("\r$prefix" . "[$status] $info");
		}
Carsten Brandt committed
892
		flush();
893
	}
Carsten Brandt committed
894

895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914
	/**
	 * Ends a progress bar that has been started by [[startProgress()]].
	 *
	 * @param string|boolean $remove This can be `false` to leave the progress bar on screen and just print a newline.
	 * If set to `true`, the line of the progress bar will be cleared. This may also be a string to be displayed instead
	 * of the progress bar.
	 * @param bool $keepPrefix whether to keep the prefix that has been specified for the progressbar when progressbar
	 * gets removed. Defaults to true.
	 * @see startProgress
	 * @see updateProgress
	 */
	public static function endProgress($remove = false, $keepPrefix = true)
	{
		if ($remove === false) {
			static::stdout(PHP_EOL);
		} else {
			if (static::streamSupportsAnsiColors(STDOUT)) {
				static::clearLine();
			}
			static::stdout("\r" . ($keepPrefix ? self::$_progressPrefix : '') . (is_string($remove) ? $remove : ''));
Carsten Brandt committed
915
		}
916 917 918 919 920
		flush();

		self::$_progressStart = null;
		self::$_progressWidth = null;
		self::$_progressPrefix = '';
Carsten Brandt committed
921
	}
Qiang Xue committed
922
}