CLI
in package
Set of static methods useful for CLI request handling.
Portions of this code were initially from the FuelPHP Framework, version 1.7.x, and used here under the MIT license they were originally made available under. Reference: http://fuelphp.com
Some of the code in this class is Windows-specific, and not possible to test using travis-ci. It has been phpunit-annotated to prevent messing up code coverage.
Tags
Table of Contents
Properties
- $readline_support : bool
- Is the readline library on the system?
- $wait_msg : string
- The message displayed at prompts.
- $background_colors : array<string, string>
- Background color list
- $foreground_colors : array<string, string>
- Foreground color list
- $height : int|null
- Height of the CLI window
- $initialized : bool
- Has the class already been initialized?
- $io : InputOutput|null
- Input and Output for CLI.
- $isColored : bool
- Whether the current stream supports colored output.
- $lastWrite : string|null
- Helps track internally whether the last output was a "write" or a "print" to keep the output clean and as expected.
- $options : array<string|int, mixed>
- $segments : array<string|int, mixed>
- List of array segments.
- $width : int|null
- Width of the CLI window
Methods
- beep() : void
- Beeps a certain number of times.
- clearScreen() : void
- Clears the screen of output
- color() : string
- Returns the given text with the correct color codes for a foreground and optionally a background color.
- error() : void
- Outputs an error to the CLI using STDERR instead of STDOUT
- generateDimensions() : void
- Populates the CLI's dimensions.
- getHeight() : int
- Attempts to determine the height of the viewable CLI window.
- getOption() : string|true|null
- Gets a single command-line option. Returns TRUE if the option exists, but doesn't have a value, and is simply acting as a flag.
- getOptions() : array<string|int, mixed>
- Returns the raw array of options found.
- getOptionString() : string
- Returns the options as a string, suitable for passing along on the CLI to other commands.
- getSegment() : string|null
- Returns an individual segment.
- getSegments() : array<string|int, mixed>
- Returns the raw array of segments found.
- getURI() : string
- Returns the command line string portions of the arguments, minus any options, as a string. This is used to pass along to the main CodeIgniter application.
- getWidth() : int
- Attempts to determine the width of the viewable CLI window.
- hasColorSupport() : bool
- Returns true if the stream resource supports colors.
- init() : void
- Static "constructor".
- input() : string
- Get input from the shell, using readline or the standard STDIN
- isWindows() : bool
- if operating system === windows
- newLine() : void
- Enter a number of empty lines
- print() : void
- Outputs a string to the CLI without any surrounding newlines.
- prompt() : string
- Asks the user for input.
- promptByKey() : string
- prompt(), but based on the option's key
- promptByMultipleKeys() : array<string|int, mixed>
- This method is the same as promptByKey(), but this method supports multiple keys, separated by commas.
- resetInputOutput() : void
- Testing purpose only
- setInputOutput() : void
- Testing purpose only
- showProgress() : void
- Displays a progress bar on the CLI. You must call it repeatedly to update it. Set $thisStep = false to erase the progress bar.
- streamSupports() : bool
- Checks whether the current stream resource supports or refers to a valid terminal type device.
- strlen() : int
- Get the number of characters in string having encoded characters and ignores styles set by the color() function
- table() : void
- Returns a well formatted table
- wait() : void
- Waits a certain number of seconds, optionally showing a wait message and waiting for a key press.
- wrap() : string
- Takes a string and writes it to the command line, wrapping to a maximum width. If no maximum width is specified, will wrap to the window's max width.
- write() : void
- Outputs a string to the cli on its own line.
- fwrite() : void
- While the library is intended for use on CLI commands, commands can be called from controllers and elsewhere so we need a way to allow them to still work.
- parseCommandLine() : void
- Parses the command line it was called from and collects all options and valid segments.
- validate() : bool
- Validate one prompt "field" at a time
- getColoredText() : string
- isZeroOptions() : void
- Validation for $options in promptByKey() and promptByMultipleKeys(). Return an error if $options is an empty array.
- printKeysAndValues() : void
- Print each key and value one by one
Properties
$readline_support
Is the readline library on the system?
Should be protected, and no longer used.
public
static bool
$readline_support
= false
Tags
$wait_msg
The message displayed at prompts.
Should be protected.
public
static string
$wait_msg
= 'Press any key to continue...'
Tags
$background_colors
Background color list
protected
static array<string, string>
$background_colors
= ['black' => '40', 'red' => '41', 'green' => '42', 'yellow' => '43', 'blue' => '44', 'magenta' => '45', 'cyan' => '46', 'light_gray' => '47']
Tags
$foreground_colors
Foreground color list
protected
static array<string, string>
$foreground_colors
= ['black' => '0;30', 'dark_gray' => '1;30', 'blue' => '0;34', 'dark_blue' => '0;34', 'light_blue' => '1;34', 'green' => '0;32', 'light_green' => '1;32', 'cyan' => '0;36', 'light_cyan' => '1;36', 'red' => '0;31', 'light_red' => '1;31', 'purple' => '0;35', 'light_purple' => '1;35', 'yellow' => '0;33', 'light_yellow' => '1;33', 'light_gray' => '0;37', 'white' => '1;37']
Tags
$height
Height of the CLI window
protected
static int|null
$height
$initialized
Has the class already been initialized?
protected
static bool
$initialized
= false
$io
Input and Output for CLI.
protected
static InputOutput|null
$io
= null
$isColored
Whether the current stream supports colored output.
protected
static bool
$isColored
= false
$lastWrite
Helps track internally whether the last output was a "write" or a "print" to keep the output clean and as expected.
protected
static string|null
$lastWrite
$options
protected
static array<string|int, mixed>
$options
= []
$segments
List of array segments.
protected
static array<string|int, mixed>
$segments
= []
$width
Width of the CLI window
protected
static int|null
$width
Methods
beep()
Beeps a certain number of times.
public
static beep([int $num = 1 ]) : void
Parameters
- $num : int = 1
-
The number of times to beep
clearScreen()
Clears the screen of output
public
static clearScreen() : void
color()
Returns the given text with the correct color codes for a foreground and optionally a background color.
public
static color(string $text, string $foreground[, string|null $background = null ][, string|null $format = null ]) : string
Parameters
- $text : string
-
The text to color
- $foreground : string
-
The foreground color
- $background : string|null = null
-
The background color
- $format : string|null = null
-
Other formatting to apply. Currently only 'underline' is understood
Return values
string —The color coded string
error()
Outputs an error to the CLI using STDERR instead of STDOUT
public
static error(string $text[, string $foreground = 'light_red' ][, string|null $background = null ]) : void
Parameters
- $text : string
- $foreground : string = 'light_red'
- $background : string|null = null
generateDimensions()
Populates the CLI's dimensions.
public
static generateDimensions() : void
getHeight()
Attempts to determine the height of the viewable CLI window.
public
static getHeight([int $default = 32 ]) : int
Parameters
- $default : int = 32
Return values
intgetOption()
Gets a single command-line option. Returns TRUE if the option exists, but doesn't have a value, and is simply acting as a flag.
public
static getOption(string $name) : string|true|null
Parameters
- $name : string
Return values
string|true|nullgetOptions()
Returns the raw array of options found.
public
static getOptions() : array<string|int, mixed>
Return values
array<string|int, mixed>getOptionString()
Returns the options as a string, suitable for passing along on the CLI to other commands.
public
static getOptionString([bool $useLongOpts = false ][, bool $trim = false ]) : string
Parameters
- $useLongOpts : bool = false
-
Use '--' for long options?
- $trim : bool = false
-
Trim final string output?
Return values
stringgetSegment()
Returns an individual segment.
public
static getSegment(int $index) : string|null
This ignores any options that might have been dispersed between valid segments in the command:
// segment(3) is 'three', not '-f' or 'anOption'
php spark one two -f anOption three
IMPORTANT: The index here is one-based instead of zero-based.
Parameters
- $index : int
Return values
string|nullgetSegments()
Returns the raw array of segments found.
public
static getSegments() : array<string|int, mixed>
Return values
array<string|int, mixed>getURI()
Returns the command line string portions of the arguments, minus any options, as a string. This is used to pass along to the main CodeIgniter application.
public
static getURI() : string
Return values
stringgetWidth()
Attempts to determine the width of the viewable CLI window.
public
static getWidth([int $default = 80 ]) : int
Parameters
- $default : int = 80
Return values
inthasColorSupport()
Returns true if the stream resource supports colors.
public
static hasColorSupport(resource $resource) : bool
This is tricky on Windows, because Cygwin, Msys2 etc. emulate pseudo terminals via named pipes, so we can only check the environment.
Reference: https://github.com/composer/xdebug-handler/blob/master/src/Process.php
Parameters
- $resource : resource
Return values
boolinit()
Static "constructor".
public
static init() : void
input()
Get input from the shell, using readline or the standard STDIN
public
static input([string|null $prefix = null ]) : string
Named options must be in the following formats: php index.php user -v --v -name=John --name=John
Parameters
- $prefix : string|null = null
-
You may specify a string with which to prompt the user.
Return values
stringisWindows()
if operating system === windows
public
static isWindows() : bool
Use is_windows()
instead
Return values
boolnewLine()
Enter a number of empty lines
public
static newLine([int $num = 1 ]) : void
Parameters
- $num : int = 1
print()
Outputs a string to the CLI without any surrounding newlines.
public
static print([string $text = '' ][, string|null $foreground = null ][, string|null $background = null ]) : void
Useful for showing repeating elements on a single line.
Parameters
- $text : string = ''
- $foreground : string|null = null
- $background : string|null = null
prompt()
Asks the user for input.
public
static prompt(string $field[, array<int, int|string>|string $options = null ][, array<string|int, mixed>|string|null $validation = null ]) : string
Usage:
// Takes any input $color = CLI::prompt('What is your favorite color?');
// Takes any input, but offers default $color = CLI::prompt('What is your favourite color?', 'white');
// Will validate options with the in_list rule and accept only if one of the list $color = CLI::prompt('What is your favourite color?', array('red','blue'));
// Do not provide options but requires a valid email $email = CLI::prompt('What is your email?', null, 'required|valid_email');
Parameters
- $field : string
-
Output "field" question
- $options : array<int, int|string>|string = null
-
String to a default value, array to a list of options (the first option will be the default value)
- $validation : array<string|int, mixed>|string|null = null
-
Validation rules
Return values
string —The user input
promptByKey()
prompt(), but based on the option's key
public
static promptByKey(array<string|int, mixed>|string $text, array<string|int, mixed> $options[, array<string|int, mixed>|string|null $validation = null ]) : string
Parameters
- $text : array<string|int, mixed>|string
-
Output "field" text or an one or two value array where the first value is the text before listing the options and the second value the text before asking to select one option. Provide empty string to omit
- $options : array<string|int, mixed>
-
A list of options (array(key => description)), the first option will be the default value
- $validation : array<string|int, mixed>|string|null = null
-
Validation rules
Return values
string —The selected key of $options
promptByMultipleKeys()
This method is the same as promptByKey(), but this method supports multiple keys, separated by commas.
public
static promptByMultipleKeys(string $text, array<string|int, mixed> $options) : array<string|int, mixed>
Parameters
- $text : string
-
Output "field" text or an one or two value array where the first value is the text before listing the options and the second value the text before asking to select one option. Provide empty string to omit
- $options : array<string|int, mixed>
-
A list of options (array(key => description)), the first option will be the default value
Return values
array<string|int, mixed> —The selected key(s) and value(s) of $options
resetInputOutput()
Testing purpose only
public
static resetInputOutput() : void
Tags
setInputOutput()
Testing purpose only
public
static setInputOutput(InputOutput $io) : void
Parameters
- $io : InputOutput
Tags
showProgress()
Displays a progress bar on the CLI. You must call it repeatedly to update it. Set $thisStep = false to erase the progress bar.
public
static showProgress([bool|int $thisStep = 1 ][, int $totalSteps = 10 ]) : void
Parameters
- $thisStep : bool|int = 1
- $totalSteps : int = 10
streamSupports()
Checks whether the current stream resource supports or refers to a valid terminal type device.
public
static streamSupports(string $function, resource $resource) : bool
Parameters
- $function : string
- $resource : resource
Return values
boolstrlen()
Get the number of characters in string having encoded characters and ignores styles set by the color() function
public
static strlen(string|null $string) : int
Parameters
- $string : string|null
Return values
inttable()
Returns a well formatted table
public
static table(array<string|int, mixed> $tbody[, array<string|int, mixed> $thead = [] ]) : void
Parameters
- $tbody : array<string|int, mixed>
-
List of rows
- $thead : array<string|int, mixed> = []
-
List of columns
wait()
Waits a certain number of seconds, optionally showing a wait message and waiting for a key press.
public
static wait(int $seconds[, bool $countdown = false ]) : void
Parameters
- $seconds : int
-
Number of seconds
- $countdown : bool = false
-
Show a countdown or not
wrap()
Takes a string and writes it to the command line, wrapping to a maximum width. If no maximum width is specified, will wrap to the window's max width.
public
static wrap([string|null $string = null ][, int $max = 0 ][, int $padLeft = 0 ]) : string
If an int is passed into $pad_left, then all strings after the first will pad with that many spaces to the left. Useful when printing short descriptions that need to start on an existing line.
Parameters
- $string : string|null = null
- $max : int = 0
- $padLeft : int = 0
Return values
stringwrite()
Outputs a string to the cli on its own line.
public
static write([string $text = '' ][, string|null $foreground = null ][, string|null $background = null ]) : void
Parameters
- $text : string = ''
- $foreground : string|null = null
- $background : string|null = null
fwrite()
While the library is intended for use on CLI commands, commands can be called from controllers and elsewhere so we need a way to allow them to still work.
protected
static fwrite(resource $handle, string $string) : void
For now, just echo the content, but look into a better solution down the road.
Parameters
- $handle : resource
- $string : string
parseCommandLine()
Parses the command line it was called from and collects all options and valid segments.
protected
static parseCommandLine() : void
validate()
Validate one prompt "field" at a time
protected
static validate(string $field, string $value, array<string|int, mixed>|string $rules) : bool
Parameters
- $field : string
-
Prompt "field" output
- $value : string
-
Input value
- $rules : array<string|int, mixed>|string
-
Validation rules
Return values
boolgetColoredText()
private
static getColoredText(string $text, string $foreground, string|null $background, string|null $format) : string
Parameters
- $text : string
- $foreground : string
- $background : string|null
- $format : string|null
Return values
stringisZeroOptions()
Validation for $options in promptByKey() and promptByMultipleKeys(). Return an error if $options is an empty array.
private
static isZeroOptions(array<string|int, mixed> $options) : void
Parameters
- $options : array<string|int, mixed>
printKeysAndValues()
Print each key and value one by one
private
static printKeysAndValues(array<string|int, mixed> $options) : void
Parameters
- $options : array<string|int, mixed>