0 follower

Class yii\helpers\BaseConsole

Inheritanceyii\helpers\BaseConsole
Subclassesyii\helpers\Console
Available since version2.0
Source Code https://github.com/yiisoft/yii2/blob/master/framework/helpers/BaseConsole.php

BaseConsole provides concrete implementation for yii\helpers\Console.

Do not use BaseConsole. Use yii\helpers\Console instead.

Public Methods

Hide inherited methods

MethodDescriptionDefined By
ansiFormat() Will return a string formatted with the given ANSI style. yii\helpers\BaseConsole
ansiFormatCode() Returns the ANSI format code. yii\helpers\BaseConsole
ansiStrlen() Returns the length of the string without ANSI color codes. yii\helpers\BaseConsole
ansiToHtml() Converts an ANSI formatted string to HTML. yii\helpers\BaseConsole
beginAnsiFormat() Echoes an ANSI format code that affects the formatting of any text that is printed afterwards. yii\helpers\BaseConsole
clearLine() Clears the line, the cursor is currently on by sending ANSI control code EL with argument 2 to the terminal. yii\helpers\BaseConsole
clearLineAfterCursor() Clears text from cursor position to the end of the line by sending ANSI control code EL with argument 0 to the terminal. yii\helpers\BaseConsole
clearLineBeforeCursor() Clears text from cursor position to the beginning of the line by sending ANSI control code EL with argument 1 to the terminal. yii\helpers\BaseConsole
clearScreen() Clears entire screen content by sending ANSI control code ED with argument 2 to the terminal. yii\helpers\BaseConsole
clearScreenAfterCursor() Clears text from cursor to the end of the screen by sending ANSI control code ED with argument 0 to the terminal. yii\helpers\BaseConsole
clearScreenBeforeCursor() Clears text from cursor to the beginning of the screen by sending ANSI control code ED with argument 1 to the terminal. yii\helpers\BaseConsole
confirm() Asks user to confirm by typing y or n. yii\helpers\BaseConsole
endAnsiFormat() Resets any ANSI format set by previous method beginAnsiFormat() Any output after this will have default text format. yii\helpers\BaseConsole
endProgress() Ends a progress bar that has been started by startProgress(). yii\helpers\BaseConsole
error() Prints text to STDERR appended with a carriage return (PHP_EOL). yii\helpers\BaseConsole
errorSummary() Generates a summary of the validation errors. yii\helpers\BaseConsole
escape() Escapes % so they don't get interpreted as color codes when the string is parsed by renderColoredString(). yii\helpers\BaseConsole
getScreenSize() Returns terminal screen size. yii\helpers\BaseConsole
hideCursor() Hides the cursor by sending ANSI DECTCEM code ?25l to the terminal. yii\helpers\BaseConsole
input() Asks the user for input. Ends when the user types a carriage return (PHP_EOL). Optionally, It also provides a prompt. yii\helpers\BaseConsole
isRunningOnWindows() Returns true if the console is running on windows. yii\helpers\BaseConsole
markdownToAnsi() Converts Markdown to be better readable in console environments by applying some ANSI format. yii\helpers\BaseConsole
moveCursorBackward() Moves the terminal cursor backward by sending ANSI control code CUB to the terminal. yii\helpers\BaseConsole
moveCursorDown() Moves the terminal cursor down by sending ANSI control code CUD to the terminal. yii\helpers\BaseConsole
moveCursorForward() Moves the terminal cursor forward by sending ANSI control code CUF to the terminal. yii\helpers\BaseConsole
moveCursorNextLine() Moves the terminal cursor to the beginning of the next line by sending ANSI control code CNL to the terminal. yii\helpers\BaseConsole
moveCursorPrevLine() Moves the terminal cursor to the beginning of the previous line by sending ANSI control code CPL to the terminal. yii\helpers\BaseConsole
moveCursorTo() Moves the cursor to an absolute position given as column and row by sending ANSI control code CUP or CHA to the terminal. yii\helpers\BaseConsole
moveCursorUp() Moves the terminal cursor up by sending ANSI control code CUU to the terminal. yii\helpers\BaseConsole
output() Prints text to STDOUT appended with a carriage return (PHP_EOL). yii\helpers\BaseConsole
prompt() Prompts the user for input and validates it. yii\helpers\BaseConsole
renderColoredString() Converts a string to ansi formatted by replacing patterns like %y (for yellow) with ansi control codes. yii\helpers\BaseConsole
restoreCursorPosition() Restores the cursor position saved with saveCursorPosition() by sending ANSI control code RCP to the terminal. yii\helpers\BaseConsole
saveCursorPosition() Saves the current cursor position by sending ANSI control code SCP to the terminal. yii\helpers\BaseConsole
scrollDown() Scrolls whole page down by sending ANSI control code SD to the terminal. yii\helpers\BaseConsole
scrollUp() Scrolls whole page up by sending ANSI control code SU to the terminal. yii\helpers\BaseConsole
select() Gives the user an option to choose from. Giving '?' as an input will show a list of options to choose from and their explanations. yii\helpers\BaseConsole
showCursor() Will show a cursor again when it has been hidden by hideCursor() by sending ANSI DECTCEM code ?25h to the terminal. yii\helpers\BaseConsole
startProgress() Starts display of a progress bar on screen. yii\helpers\BaseConsole
stderr() Prints a string to STDERR. yii\helpers\BaseConsole
stdin() Gets input from STDIN and returns a string right-trimmed for EOLs. yii\helpers\BaseConsole
stdout() Prints a string to STDOUT. yii\helpers\BaseConsole
streamSupportsAnsiColors() Returns true if the stream supports colorization. ANSI colors are disabled if not supported by the stream. yii\helpers\BaseConsole
stripAnsiFormat() Strips ANSI control codes from a string. yii\helpers\BaseConsole
updateProgress() Updates a progress bar that has been started by startProgress(). yii\helpers\BaseConsole
wrapText() Word wrap text with indentation to fit the screen size. yii\helpers\BaseConsole
xtermBgColor() Returns the ansi format code for xterm background color. yii\helpers\BaseConsole
xtermFgColor() Returns the ansi format code for xterm foreground color. yii\helpers\BaseConsole

Method Details

ansiFormat() public static method

Will return a string formatted with the given ANSI style.

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

The string to be formatted

$format array

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.

ansiFormatCode() public static method

Returns the ANSI format code.

public static string ansiFormatCode ( $format )
$format array

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.

ansiStrlen() public static method

Returns the length of the string without ANSI color codes.

public static integer ansiStrlen ( $string )
$string string

The string to measure

return integer

The length of the string not counting ANSI format characters

ansiToHtml() public static method

Converts an ANSI formatted string to HTML.

Note: xTerm 256 bit colors are currently not supported.

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

The string to convert.

$styleMap array

An 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.

return string

HTML representation of the ANSI formatted string

beginAnsiFormat() public static method

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

See also:

public static void beginAnsiFormat ( $format )
$format array

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.

clearLine() public static method

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 void clearLine ( )
clearLineAfterCursor() public static method

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 void clearLineAfterCursor ( )
clearLineBeforeCursor() public static method

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 void clearLineBeforeCursor ( )
clearScreen() public static method

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 void clearScreen ( )
clearScreenAfterCursor() public static method

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 void clearScreenAfterCursor ( )
clearScreenBeforeCursor() public static method

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 void clearScreenBeforeCursor ( )
confirm() public static method

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";
}
public static boolean confirm ( $message, $default false )
$message string

To print out before waiting for user input

$default boolean

This value is returned if no selection is made.

return boolean

Whether user confirmed

endAnsiFormat() public static method

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])
public static void endAnsiFormat ( )
endProgress() public static method

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

See also:

public static void endProgress ( $remove false, $keepPrefix true )
$remove string|boolean

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.

$keepPrefix boolean

Whether to keep the prefix that has been specified for the progressbar when progressbar gets removed. Defaults to true.

error() public static method

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

public static integer|boolean error ( $string null )
$string string

The text to print

return integer|boolean

Number of bytes printed or false on error.

errorSummary() public static method (available since version 2.0.14)

Generates a summary of the validation errors.

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

The model(s) whose validation errors are to be displayed.

$options array

The 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.
return string

The generated error summary

escape() public static method

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

public static string escape ( $string )
$string string

String to escape

getScreenSize() public static method

Returns terminal screen size.

Usage:

list($width, $height) = ConsoleHelper::getScreenSize();
public static array|boolean getScreenSize ( $refresh false )
$refresh boolean

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.

return array|boolean

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

hideCursor() public static method

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.

public static void hideCursor ( )
input() public static method

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

public static string input ( $prompt null )
$prompt string

The prompt to display before waiting for input (optional)

return string

The user's input

isRunningOnWindows() public static method

Returns true if the console is running on windows.

public static boolean isRunningOnWindows ( )
markdownToAnsi() public static method

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

public static string markdownToAnsi ( $markdown )
$markdown string

The markdown string.

return string

The parsed result as ANSI formatted string.

moveCursorBackward() public static method

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.

public static void moveCursorBackward ( $steps 1 )
$steps integer

Number of steps the cursor should be moved backward

moveCursorDown() public static method

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.

public static void moveCursorDown ( $rows 1 )
$rows integer

Number of rows the cursor should be moved down

moveCursorForward() public static method

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.

public static void moveCursorForward ( $steps 1 )
$steps integer

Number of steps the cursor should be moved forward

moveCursorNextLine() public static method

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

public static void moveCursorNextLine ( $lines 1 )
$lines integer

Number of lines the cursor should be moved down

moveCursorPrevLine() public static method

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

public static void moveCursorPrevLine ( $lines 1 )
$lines integer

Number of lines the cursor should be moved up

moveCursorTo() public static method

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

public static void moveCursorTo ( $column, $row null )
$column integer

1-based column number, 1 is the left edge of the screen.

$row integer|null

1-based row number, 1 is the top edge of the screen. if not set, will move cursor only in current line.

moveCursorUp() public static method

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.

public static void moveCursorUp ( $rows 1 )
$rows integer

Number of rows the cursor should be moved up

output() public static method

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

public static integer|boolean output ( $string null )
$string string

The text to print

return integer|boolean

Number of bytes printed or false on error.

prompt() public static method

Prompts the user for input and validates it.

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

Prompt string

$options array

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

renderColoredString() public static method

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.

             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 %

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

public static string renderColoredString ( $string, $colored true )
$string string

String to convert

$colored boolean

Should the string be colored?

restoreCursorPosition() public static method

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

public static void restoreCursorPosition ( )
saveCursorPosition() public static method

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

Position can then be restored with restoreCursorPosition().

public static void saveCursorPosition ( )
scrollDown() public static method

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.

public static void scrollDown ( $lines 1 )
$lines integer

Number of lines to scroll down

scrollUp() public static method

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.

public static void scrollUp ( $lines 1 )
$lines integer

Number of lines to scroll up

select() public static method

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

public static string select ( $prompt, $options = [] )
$prompt string

The prompt message

$options array

Key-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.

return string

An option character the user chose

showCursor() public static method

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

public static void showCursor ( )
startProgress() public static method

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:

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); `

See also:

public static void startProgress ( $done, $total, $prefix '', $width null )
$done integer

The number of items that are completed.

$total integer

The total value of items that are to be done.

$prefix string

An optional string to display before the progress bar. Default to empty string which results in no prefix to be displayed.

$width integer|boolean

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().

stderr() public static method

Prints a string to STDERR.

public static integer|boolean stderr ( $string )
$string string

The string to print

return integer|boolean

Number of bytes printed or false on error

stdin() public static method

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

public static string stdin ( $raw false )
$raw boolean

If set to true, returns the raw string without trimming

return string

The string read from stdin

stdout() public static method

Prints a string to STDOUT.

public static integer|boolean stdout ( $string )
$string string

The string to print

return integer|boolean

Number of bytes printed or false on error

streamSupportsAnsiColors() public static method

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

  • windows without ansicon
  • not tty consoles
public static boolean streamSupportsAnsiColors ( $stream )
$stream mixed
return boolean

True if the stream supports ANSI colors, otherwise false.

stripAnsiFormat() public static method

Strips ANSI control codes from a string.

public static string stripAnsiFormat ( $string )
$string string

String to strip

updateProgress() public static method

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

See also:

public static void updateProgress ( $done, $total, $prefix null )
$done integer

The number of items that are completed.

$total integer

The total value of items that are to be done.

$prefix string

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.

wrapText() public static method (available since version 2.0.4)

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.
public static string wrapText ( $text, $indent 0, $refresh false )
$text string

The text to be wrapped

$indent integer

Number of spaces to use for indentation.

$refresh boolean

Whether to force refresh of screen size. This will be passed to getScreenSize().

return string

The wrapped text.

xtermBgColor() public static method

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().

See also http://en.wikipedia.org/wiki/Talk:ANSI_escape_code#xterm-256colors.

public static string xtermBgColor ( $colorCode )
$colorCode integer

Xterm color code

xtermFgColor() public static method

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().

See also http://en.wikipedia.org/wiki/Talk:ANSI_escape_code#xterm-256colors.

public static string xtermFgColor ( $colorCode )
$colorCode integer

Xterm color code