Skip to content
PHP Ecosystem
Explore

BaseConsole

API reference › yii › helpers › BaseConsole

classyii\helpers\BaseConsole
Since2.0
Sourceframework/helpers/BaseConsole.php
1 subclass

BaseConsole provides concrete implementation for Console.

Do not use BaseConsole. Use Console instead.

MethodDescriptionDefined by
ansiColorizedSubstr() staticReturns the portion with ANSI color codes of string specified by the start and length parameters.BaseConsole
ansiFormat() staticWill return a string formatted with the given ANSI style.BaseConsole
ansiFormatCode() staticReturns the ANSI format code.BaseConsole
ansiStrlen() staticReturns the length of the string without ANSI color codes.BaseConsole
ansiStrwidth() staticReturns the width of the string without ANSI color codes.BaseConsole
ansiToHtml() staticConverts an ANSI formatted string to HTML.BaseConsole
beginAnsiFormat() staticEchoes an ANSI format code that affects the formatting of any text that is printed afterwards.BaseConsole
clearLine() staticClears the line, the cursor is currently on by sending ANSI control code EL with argument 2 to the terminal.BaseConsole
clearLineAfterCursor() staticClears text from cursor position to the end of the line by sending ANSI control code EL with argument 0 to the terminal.BaseConsole
clearLineBeforeCursor() staticClears text from cursor position to the beginning of the line by sending ANSI control code EL with argument 1 to the terminal.BaseConsole
clearScreen() staticClears entire screen content by sending ANSI control code ED with argument 2 to the terminal.BaseConsole
clearScreenAfterCursor() staticClears text from cursor to the end of the screen by sending ANSI control code ED with argument 0 to the terminal.BaseConsole
clearScreenBeforeCursor() staticClears text from cursor to the beginning of the screen by sending ANSI control code ED with argument 1 to the terminal.BaseConsole
confirm() staticAsks user to confirm by typing y or n.BaseConsole
endAnsiFormat() staticResets any ANSI format set by previous method beginAnsiFormat() Any output after this will have default text format.BaseConsole
endProgress() staticEnds a progress bar that has been started by startProgress().BaseConsole
error() staticPrints text to STDERR appended with a carriage return (PHP_EOL).BaseConsole
errorSummary() staticGenerates a summary of the validation errors.BaseConsole
escape() staticEscapes % so they don’t get interpreted as color codes when the string is parsed by renderColoredString().BaseConsole
getScreenSize() staticReturns terminal screen size.BaseConsole
hideCursor() staticHides the cursor by sending ANSI DECTCEM code ?25l to the terminal.BaseConsole
input() staticAsks the user for input. Ends when the user types a carriage return (PHP_EOL). Optionally, It also provides a prompt.BaseConsole
isRunningOnWindows() staticReturns true if the console is running on windows.BaseConsole
markdownToAnsi() staticConverts Markdown to be better readable in console environments by applying some ANSI format.BaseConsole
moveCursorBackward() staticMoves the terminal cursor backward by sending ANSI control code CUB to the terminal.BaseConsole
moveCursorDown() staticMoves the terminal cursor down by sending ANSI control code CUD to the terminal.BaseConsole
moveCursorForward() staticMoves the terminal cursor forward by sending ANSI control code CUF to the terminal.BaseConsole
moveCursorNextLine() staticMoves the terminal cursor to the beginning of the next line by sending ANSI control code CNL to the terminal.BaseConsole
moveCursorPrevLine() staticMoves the terminal cursor to the beginning of the previous line by sending ANSI control code CPL to the terminal.BaseConsole
moveCursorTo() staticMoves the cursor to an absolute position given as column and row by sending ANSI control code CUP or CHA to the terminal.BaseConsole
moveCursorUp() staticMoves the terminal cursor up by sending ANSI control code CUU to the terminal.BaseConsole
output() staticPrints text to STDOUT appended with a carriage return (PHP_EOL).BaseConsole
prompt() staticPrompts the user for input and validates it.BaseConsole
renderColoredString() staticConverts a string to ansi formatted by replacing patterns like %y (for yellow) with ansi control codes.BaseConsole
restoreCursorPosition() staticRestores the cursor position saved with saveCursorPosition() by sending ANSI control code RCP to the terminal.BaseConsole
saveCursorPosition() staticSaves the current cursor position by sending ANSI control code SCP to the terminal.BaseConsole
scrollDown() staticScrolls whole page down by sending ANSI control code SD to the terminal.BaseConsole
scrollUp() staticScrolls whole page up by sending ANSI control code SU to the terminal.BaseConsole
select() staticGives the user an option to choose from. Giving ’?’ as an input will show a list of options to choose from and their explanations.BaseConsole
showCursor() staticWill show a cursor again when it has been hidden by hideCursor() by sending ANSI DECTCEM code ?25h to the terminal.BaseConsole
startProgress() staticStarts display of a progress bar on screen.BaseConsole
stderr() staticPrints a string to STDERR.BaseConsole
stdin() staticGets input from STDIN and returns a string right-trimmed for EOLs.BaseConsole
stdout() staticPrints a string to STDOUT.BaseConsole
streamSupportsAnsiColors() staticReturns true if the stream supports colorization. ANSI colors are disabled if not supported by the stream.BaseConsole
stripAnsiFormat() staticStrips ANSI control codes from a string.BaseConsole
updateProgress() staticUpdates a progress bar that has been started by startProgress().BaseConsole
wrapText() staticWord wrap text with indentation to fit the screen size.BaseConsole
xtermBgColor() staticReturns the ansi format code for xterm background color.BaseConsole
xtermFgColor() staticReturns the ansi format code for xterm foreground color.BaseConsole
ConstantValueDescriptionDefined by
FG_BLACK30BaseConsole
FG_RED31BaseConsole
FG_GREEN32BaseConsole
FG_YELLOW33BaseConsole
FG_BLUE34BaseConsole
FG_PURPLE35BaseConsole
FG_CYAN36BaseConsole
FG_GREY37BaseConsole
BG_BLACK40BaseConsole
BG_RED41BaseConsole
BG_GREEN42BaseConsole
BG_YELLOW43BaseConsole
BG_BLUE44BaseConsole
BG_PURPLE45BaseConsole
BG_CYAN46BaseConsole
BG_GREY47BaseConsole
RESET0BaseConsole
NORMAL0BaseConsole
BOLD1BaseConsole
ITALIC3BaseConsole
UNDERLINE4BaseConsole
BLINK5BaseConsole
NEGATIVE7BaseConsole
CONCEALED8BaseConsole
CROSSED_OUT9BaseConsole
FRAMED51BaseConsole
ENCIRCLED52BaseConsole
OVERLINED53BaseConsole
public static function ansiColorizedSubstr(string $string, int $start, int $length): string

Returns the portion with ANSI color codes of string specified by the start and length parameters.

If string has color codes, then will be return “TEXT_COLOR + TEXT_STRING + DEFAULT_COLOR”, else will be simple “TEXT_STRING”.

Parameters

ParameterTypeDescription
$stringstring
$startint
$lengthint

Returns

string

public static function ansiFormat(string $string, array $format = []): string

Will return a string formatted with the given ANSI style.

Parameters

ParameterTypeDescription
$stringstringThe string to be formatted
$formatarrayAn array containing formatting values. You can pass any of the FG_*, BG_* and TEXT_* constants and also xtermFgColor() and xtermBgColor() to specify a format.

Returns

string

public static function ansiFormatCode(array $format): string

Returns the ANSI format code.

Parameters

ParameterTypeDescription
$formatarrayAn array containing formatting values. You can pass any of the FG_*, BG_* and TEXT_* constants and also xtermFgColor() and xtermBgColor() to specify a format.

Returns

string: The ANSI format code according to the given formatting constants.

public static function ansiStrlen(string $string): int

Returns the length of the string without ANSI color codes.

Parameters

ParameterTypeDescription
$stringstringThe string to measure

Returns

int: The length of the string not counting ANSI format characters

public static function ansiStrwidth(string $string): int

Returns the width of the string without ANSI color codes.

Parameters

ParameterTypeDescription
$stringstringThe string to measure

Returns

int: The width of the string not counting ANSI format characters

Since

2.0.36

public static function ansiToHtml(string $string, array $styleMap = []): string

Converts an ANSI formatted string to HTML.

Note: xTerm 256 bit colors are currently not supported.

Parameters

ParameterTypeDescription
$stringstringThe string to convert.
$styleMaparrayAn optional mapping of ANSI control codes such as FG_COLOR or BOLD to a set of css style definitions. The CSS style definitions are represented as an array where the array keys correspond to the css style attribute names and the values are the css values. values may be arrays that will be merged and imploded with ' ' when rendered.

Returns

string: HTML representation of the ANSI formatted string

public static function beginAnsiFormat(array $format): mixed

Echoes an ANSI format code that affects the formatting of any text that is printed afterwards.

Parameters

ParameterTypeDescription
$formatarrayAn array containing formatting values. You can pass any of the FG_*, BG_* and TEXT_* constants and also xtermFgColor() and xtermBgColor() to specify a format.

Returns

mixed

See also

public static function clearLine(): mixed

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.

Returns

mixed

public static function clearLineAfterCursor(): mixed

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.

Returns

mixed

public static function clearLineBeforeCursor(): mixed

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.

Returns

mixed

public static function clearScreen(): mixed

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.

Returns

mixed

public static function clearScreenAfterCursor(): mixed

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.

Returns

mixed

public static function clearScreenBeforeCursor(): mixed

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.

Returns

mixed

public static function confirm(string $message, bool $default = false): bool

Asks user to confirm by typing y or n.

A typical usage looks like the following:

if (Console::confirm("Are you sure?")) {
echo "user typed yes\n";
} else {
echo "user typed no\n";
}

Parameters

ParameterTypeDescription
$messagestringTo print out before waiting for user input
$defaultboolThis value is returned if no selection is made.

Returns

bool: Whether user confirmed

public static function endAnsiFormat(): mixed

Resets any ANSI format set by previous method beginAnsiFormat() Any output after this will have default text format.

This is equal to calling.

echo Console::ansiFormatCode([Console::RESET])

Returns

mixed

public static function endProgress(string|bool $remove = false, bool $keepPrefix = true): mixed

Ends a progress bar that has been started by startProgress().

Parameters

ParameterTypeDescription
$removestring|boolThis 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.
$keepPrefixboolWhether to keep the prefix that has been specified for the progressbar when progressbar gets removed. Defaults to true.

Returns

mixed

See also

public static function error(string|null $string = null): int|bool

Prints text to STDERR appended with a carriage return (PHP_EOL).

Parameters

ParameterTypeDescription
$stringstring|nullThe text to print

Returns

int|bool: Number of bytes printed or false on error.

public static function errorSummary(yii\base\Model|yii\base\Model[] $models, array $options = []): string

Generates a summary of the validation errors.

Parameters

ParameterTypeDescription
$modelsyii\base\Model|yii\base\Model[]The model(s) whose validation errors are to be displayed.
$optionsarrayThe tag options in terms of name-value pairs. The following options are specially handled: - showAllErrors: boolean, if set to true every error message for each attribute will be shown otherwise only the first error message for each attribute will be shown. Defaults to false.

Returns

string: The generated error summary

Since

2.0.14

public static function escape(string $string): string

Escapes % so they don’t get interpreted as color codes when the string is parsed by renderColoredString().

Parameters

ParameterTypeDescription
$stringstringString to escape

Returns

string

public static function getScreenSize(bool $refresh = false): array|bool

Returns terminal screen size.

Usage:

list($width, $height) = ConsoleHelper::getScreenSize();

Parameters

ParameterTypeDescription
$refreshboolWhether 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.

Returns

array|bool: An array of ($width, $height) or false when it was not able to determine size.

public static function hideCursor(): mixed

Hides the cursor by sending ANSI DECTCEM code ?25l to the terminal.

Use showCursor() to bring it back. Do not forget to show cursor when your application exits. Cursor might stay hidden in terminal after exit.

Returns

mixed

public static function input(string|null $prompt = null): string

Asks the user for input. Ends when the user types a carriage return (PHP_EOL). Optionally, It also provides a prompt.

Parameters

ParameterTypeDescription
$promptstring|nullThe prompt to display before waiting for input (optional)

Returns

string: The user’s input

public static function isRunningOnWindows(): bool

Returns true if the console is running on windows.

Returns

bool

public static function markdownToAnsi(string $markdown): string

Converts Markdown to be better readable in console environments by applying some ANSI format.

Parameters

ParameterTypeDescription
$markdownstringThe markdown string.

Returns

string: The parsed result as ANSI formatted string.

public static function moveCursorBackward(int $steps = 1): mixed

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.

Parameters

ParameterTypeDescription
$stepsintNumber of steps the cursor should be moved backward

Returns

mixed

public static function moveCursorDown(int $rows = 1): mixed

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.

Parameters

ParameterTypeDescription
$rowsintNumber of rows the cursor should be moved down

Returns

mixed

public static function moveCursorForward(int $steps = 1): mixed

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.

Parameters

ParameterTypeDescription
$stepsintNumber of steps the cursor should be moved forward

Returns

mixed

public static function moveCursorNextLine(int $lines = 1): mixed

Moves the terminal cursor to the beginning of the next line by sending ANSI control code CNL to the terminal.

Parameters

ParameterTypeDescription
$linesintNumber of lines the cursor should be moved down

Returns

mixed

public static function moveCursorPrevLine(int $lines = 1): mixed

Moves the terminal cursor to the beginning of the previous line by sending ANSI control code CPL to the terminal.

Parameters

ParameterTypeDescription
$linesintNumber of lines the cursor should be moved up

Returns

mixed

public static function moveCursorTo(int $column, int|null $row = null): mixed

Moves the cursor to an absolute position given as column and row by sending ANSI control code CUP or CHA to the terminal.

Parameters

ParameterTypeDescription
$columnint1-based column number, 1 is the left edge of the screen.
$rowint|null1-based row number, 1 is the top edge of the screen. if not set, will move cursor only in current line.

Returns

mixed

public static function moveCursorUp(int $rows = 1): mixed

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.

Parameters

ParameterTypeDescription
$rowsintNumber of rows the cursor should be moved up

Returns

mixed

public static function output(string|null $string = null): int|bool

Prints text to STDOUT appended with a carriage return (PHP_EOL).

Parameters

ParameterTypeDescription
$stringstring|nullThe text to print

Returns

int|bool: Number of bytes printed or false on error.

public static function prompt(string $text, array $options = []): string

Prompts the user for input and validates it.

Parameters

ParameterTypeDescription
$textstringPrompt string
$optionsarrayThe 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.

Returns

string: The user input

public static function renderColoredString(string $string, bool $colored = true): string

Converts a string to ansi formatted by replacing patterns like %y (for yellow) with ansi control codes.

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 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 color codes will just be removed (And %% will be transformed into %)

Parameters

ParameterTypeDescription
$stringstringString to convert
$coloredboolShould the string be colored?

Returns

string

public static function restoreCursorPosition(): mixed

Restores the cursor position saved with saveCursorPosition() by sending ANSI control code RCP to the terminal.

Returns

mixed

public static function saveCursorPosition(): mixed

Saves the current cursor position by sending ANSI control code SCP to the terminal.

Position can then be restored with restoreCursorPosition().

Returns

mixed

public static function scrollDown(int $lines = 1): mixed

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.

Parameters

ParameterTypeDescription
$linesintNumber of lines to scroll down

Returns

mixed

public static function scrollUp(int $lines = 1): mixed

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.

Parameters

ParameterTypeDescription
$linesintNumber of lines to scroll up

Returns

mixed

public static function select(string $prompt, array $options = [], string|null $default = null): string

Gives the user an option to choose from. Giving ’?’ as an input will show a list of options to choose from and their explanations.

Parameters

ParameterTypeDescription
$promptstringThe prompt message
$optionsarrayKey-value array of options to choose from. Key is what is inputed and used, value is what’s displayed to end user by help command.
$defaultstring|nullValue to use when the user doesn’t provide an option. If the default is null, the user is required to select an option.

Returns

string: An option character the user chose

public static function showCursor(): mixed

Will show a cursor again when it has been hidden by hideCursor() by sending ANSI DECTCEM code ?25h to the terminal.

Returns

mixed

public static function startProgress(int $done, int $total, string $prefix = '', int|float|bool|null $width = null): mixed

Starts display of a progress bar on screen.

This bar will be updated by updateProgress() and may be ended by endProgress().

The following example shows a simple usage of a progress bar:

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):

Console::startProgress(0, 1000, 'Counting objects: ', false);
for ($n = 1; $n <= 1000; $n++) {
usleep(1000);
Console::updateProgress($n, 1000);
}
Console::endProgress("done." . PHP_EOL);

Parameters

ParameterTypeDescription
$doneintThe number of items that are completed.
$totalintThe total value of items that are to be done.
$prefixstringAn optional string to display before the progress bar. Default to empty string which results in no prefix to be displayed.
$widthint|float|bool|nullOptional 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().

Returns

mixed

See also

public static function stderr(string $string): int|bool

Prints a string to STDERR.

Parameters

ParameterTypeDescription
$stringstringThe string to print

Returns

int|bool: Number of bytes printed or false on error

public static function stdin(bool $raw = false): string

Gets input from STDIN and returns a string right-trimmed for EOLs.

Parameters

ParameterTypeDescription
$rawboolIf set to true, returns the raw string without trimming

Returns

string: The string read from stdin

public static function stdout(string $string): int|bool

Prints a string to STDOUT.

Parameters

ParameterTypeDescription
$stringstringThe string to print

Returns

int|bool: Number of bytes printed or false on error

public static function streamSupportsAnsiColors(mixed $stream): bool

Returns true if the stream supports colorization. ANSI colors are disabled if not supported by the stream.

  • windows without ansicon
  • not tty consoles

Parameters

ParameterTypeDescription
$streammixed

Returns

bool: True if the stream supports ANSI colors, otherwise false.

public static function stripAnsiFormat(string $string): string

Strips ANSI control codes from a string.

Parameters

ParameterTypeDescription
$stringstringString to strip

Returns

string

public static function updateProgress(int $done, int $total, string|null $prefix = null): mixed

Updates a progress bar that has been started by startProgress().

Parameters

ParameterTypeDescription
$doneintThe number of items that are completed.
$totalintThe total value of items that are to be done.
$prefixstring|nullAn 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.

Returns

mixed

See also

public static function wrapText(string $text, int $indent = 0, bool $refresh = false): string

Word wrap text with indentation to fit the screen size.

If screen size could not be detected, or the indentation is greater than the screen size, the text will not be wrapped.

The first line will not be indented, so Console::wrapText("Lorem ipsum dolor sit amet.", 4) will result in the following output, given the screen width is 16 characters:

Lorem ipsum
dolor sit
amet.

Parameters

ParameterTypeDescription
$textstringThe text to be wrapped
$indentintNumber of spaces to use for indentation.
$refreshboolWhether to force refresh of screen size. This will be passed to getScreenSize().

Returns

string: The wrapped text.

Since

2.0.4

public static function xtermBgColor(int $colorCode): string

Returns the ansi format code for xterm background color.

You can pass the return value of this to one of the formatting methods: ansiFormat(), ansiFormatCode(), beginAnsiFormat().

Parameters

ParameterTypeDescription
$colorCodeintXterm color code

Returns

string

See also

public static function xtermFgColor(int $colorCode): string

Returns the ansi format code for xterm foreground color.

You can pass the return value of this to one of the formatting methods: ansiFormat(), ansiFormatCode(), beginAnsiFormat().

Parameters

ParameterTypeDescription
$colorCodeintXterm color code

Returns

string

See also