PHP Class yii\helpers\BaseConsole

Do not use BaseConsole. Use [[Console]] instead.
Since: 2.0
Author: Carsten Brandt ([email protected])
Show file Open project: yiisoft/yii2 Class Usage Examples

Public Methods

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

Method Details

ansiFormat() public static method

Will return a string formatted with the given ANSI style
public static ansiFormat ( string $string, array $format = [] ) : string
$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.
return string

ansiFormatCode() public static method

Returns the ANSI format code.
public static ansiFormatCode ( array $format ) : string
$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 ansiStrlen ( string $string ) : integer
$string string the string to measure
return integer the length of the string not counting ANSI format characters

ansiToHtml() public static method

Note: xTerm 256 bit colors are currently not supported.
public static ansiToHtml ( string $string, array $styleMap = [] ) : string
$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: ansiFormatCode()
See also: endAnsiFormat()
public static beginAnsiFormat ( array $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

Cursor position will not be changed.
public static clearLine ( )

clearLineAfterCursor() public static method

Cursor position will not be changed.
public static clearLineAfterCursor ( )

clearLineBeforeCursor() public static method

Cursor position will not be changed.
public static clearLineBeforeCursor ( )

clearScreen() public static method

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

clearScreenAfterCursor() public static method

Cursor position will not be changed.
public static clearScreenAfterCursor ( )

clearScreenBeforeCursor() public static method

Cursor position will not be changed.
public static clearScreenBeforeCursor ( )

confirm() public static method

Asks user to confirm by typing y or n.
public static confirm ( string $message, boolean $default = false ) : boolean
$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

This is equal to calling php echo Console::ansiFormatCode([Console::RESET])
public static endAnsiFormat ( )

endProgress() public static method

Ends a progress bar that has been started by BaseConsole::startProgress.
See also: startProgress
See also: updateProgress
public static endProgress ( string | boolean $remove = false, boolean $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 error ( string $string = null ) : integer | boolean
$string string the text to print
return integer | boolean number of bytes printed or false on error.

escape() public static method

Escapes % so they don't get interpreted as color codes when the string is parsed by [[renderColoredString]]
public static escape ( string $string ) : string
$string string String to escape
return string

getScreenSize() public static method

Usage: list($width, $height) = ConsoleHelper::getScreenSize();
public static getScreenSize ( boolean $refresh = false ) : array | boolean
$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

Use BaseConsole::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 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 input ( string $prompt = null ) : string
$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 isRunningOnWindows ( ) : boolean
return boolean

markdownToAnsi() public static method

Converts Markdown to be better readable in console environments by applying some ANSI format
public static markdownToAnsi ( string $markdown ) : string
$markdown string the markdown string.
return string the parsed result as ANSI formatted string.

moveCursorBackward() public static method

If the cursor is already at the edge of the screen, this has no effect.
public static moveCursorBackward ( integer $steps = 1 )
$steps integer number of steps the cursor should be moved backward

moveCursorDown() public static method

If the cursor is already at the edge of the screen, this has no effect.
public static moveCursorDown ( integer $rows = 1 )
$rows integer number of rows the cursor should be moved down

moveCursorForward() public static method

If the cursor is already at the edge of the screen, this has no effect.
public static moveCursorForward ( integer $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 moveCursorNextLine ( integer $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 moveCursorPrevLine ( integer $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 moveCursorTo ( integer $column, integer | null $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

If the cursor is already at the edge of the screen, this has no effect.
public static moveCursorUp ( integer $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 output ( string $string = null ) : integer | boolean
$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 prompt ( string $text, array $options = [] ) : string
$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

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 renderColoredString ( string $string, boolean $colored = true ) : string
$string string String to convert
$colored boolean Should the string be colored?
return string

restoreCursorPosition() public static method

Restores the cursor position saved with BaseConsole::saveCursorPosition by sending ANSI control code RCP to the terminal.
public static restoreCursorPosition ( )

saveCursorPosition() public static method

Position can then be restored with BaseConsole::restoreCursorPosition.
public static saveCursorPosition ( )

scrollDown() public static method

New lines are added at the top. This is not supported by ANSI.SYS used in windows.
public static scrollDown ( integer $lines = 1 )
$lines integer number of lines to scroll down

scrollUp() public static method

New lines are added at the bottom. This is not supported by ANSI.SYS used in windows.
public static scrollUp ( integer $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 select ( string $prompt, array $options = [] ) : string
$prompt string the prompt message
$options array Key-value array of options to choose from
return string An option character the user chose

showCursor() public static method

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

startProgress() public static method

This bar will be updated by BaseConsole::updateProgress and my be ended by BaseConsole::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);
See also: startProgress
See also: updateProgress
See also: endProgress
public static startProgress ( integer $done, integer $total, string $prefix = '', integer | boolean $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 stderr ( string $string ) : integer | boolean
$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 stdin ( boolean $raw = false ) : string
$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 stdout ( string $string ) : integer | boolean
$string string the string to print
return integer | boolean Number of bytes printed or false on error

streamSupportsAnsiColors() public static method

- windows without ansicon - not tty consoles
public static streamSupportsAnsiColors ( mixed $stream ) : boolean
$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 stripAnsiFormat ( string $string ) : string
$string string String to strip
return string

updateProgress() public static method

Updates a progress bar that has been started by BaseConsole::startProgress.
See also: startProgress
See also: endProgress
public static updateProgress ( integer $done, integer $total, string $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

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.
Since: 2.0.4
public static wrapText ( string $text, integer $indent, boolean $refresh = false ) : string
$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

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 xtermBgColor ( integer $colorCode ) : string
$colorCode integer xterm color code
return string

xtermFgColor() public static method

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 xtermFgColor ( integer $colorCode ) : string
$colorCode integer xterm color code
return string