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.
Some of the methods require keyboard input, and are not unit-testable as a result: input() and prompt(). validate() is internal, and not testable if prompt() isn't. The wait() method is mostly testable, as long as you don't give it an argument of "0". These have been flagged to ignore for code coverage purposes.
Table of Contents
- $readline_support : bool
- Is the readline library on the system?
- $wait_msg : string
- The message displayed at prompts.
- $background_colors : array<string|int, mixed>
- Background color list
- $foreground_colors : array<string|int, mixed>
- Foreground color list
- $height : int|null
- Height of the CLI window
- $initialized : bool
- Has the class already been initialized?
- $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
- beep() : mixed
- 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() : mixed
- 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() : bool|mixed|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() : mixed|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() : mixed
- 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() : mixed
- Outputs a string to the CLI without any surrounding newlines.
- prompt() : string
- Asks the user for input.
- showProgress() : mixed
- 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() : mixed
- 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() : mixed
- Outputs a string to the cli on it's 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() : mixed
- Parses the command line it was called from and collects all options and valid segments.
- validate() : bool
- Validate one prompt "field" at a time
Properties
$readline_support
Is the readline library on the system?
public
static bool
$readline_support
= false
$wait_msg
The message displayed at prompts.
public
static string
$wait_msg
= 'Press any key to continue...'
$background_colors
Background color list
protected
static array<string|int, mixed>
$background_colors
= ['black' => '40', 'red' => '41', 'green' => '42', 'yellow' => '43', 'blue' => '44', 'magenta' => '45', 'cyan' => '46', 'light_gray' => '47']
$foreground_colors
Foreground color list
protected
static array<string|int, mixed>
$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']
$height
Height of the CLI window
protected
static int|null
$height
$initialized
Has the class already been initialized?
protected
static bool
$initialized
= false
$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 ]) : mixed
Parameters
- $num : int = 1
-
The number of times to beep
Return values
mixed —clearScreen()
Clears the screen of output
public
static clearScreen() : void
Tags
Return values
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 $background = null ][, string $format = null ]) : string
Parameters
- $text : string
-
The text to color
- $foreground : string
-
The foreground color
- $background : string = null
-
The background color
- $format : string = 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 ]) : mixed
Parameters
- $text : string
-
The text to output, or array of errors
- $foreground : string = 'light_red'
- $background : string|null = null
Return values
mixed —generateDimensions()
Populates the CLI's dimensions.
public
static generateDimensions() : void
Return values
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
int —getOption()
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) : bool|mixed|null
Parameters
- $name : string
Return values
bool|mixed|null —getOptions()
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
string —getSegment()
Returns an individual segment.
public
static getSegment(int $index) : mixed|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
mixed|null —getSegments()
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
string —getWidth()
Attempts to determine the width of the viewable CLI window.
public
static getWidth([int $default = 80 ]) : int
Parameters
- $default : int = 80
Return values
int —hasColorSupport()
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
bool —init()
Static "constructor".
public
static init() : mixed
Return values
mixed —input()
Get input from the shell, using readline or the standard STDIN
public
static input([string $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
Tags
Return values
string —isWindows()
if operating system === windows
public
static isWindows() : bool
Return values
bool —newLine()
Enter a number of empty lines
public
static newLine([int $num = 1 ]) : void
Parameters
- $num : int = 1
-
Number of lines to output
Return values
void —print()
Outputs a string to the CLI without any surrounding newlines.
public
static print([string $text = '' ][, string|null $foreground = null ][, string|null $background = null ]) : mixed
Useful for showing repeating elements on a single line.
Parameters
- $text : string = ''
- $foreground : string|null = null
- $background : string|null = null
Return values
mixed —prompt()
Asks the user for input.
public
static prompt(string $field[, string|array<string|int, mixed> $options = null ][, string|array<string|int, mixed> $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 : string|array<string|int, mixed> = null
-
String to a default value, array to a list of options (the first option will be the default value)
- $validation : string|array<string|int, mixed> = null
-
Validation rules
Tags
Return values
string —The user input
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([int|bool $thisStep = 1 ][, int $totalSteps = 10 ]) : mixed
Parameters
- $thisStep : int|bool = 1
- $totalSteps : int = 10
Return values
mixed —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
bool —strlen()
Get the number of characters in string having encoded characters and ignores styles set by the color() function
public
static strlen(string $string) : int
Parameters
- $string : string
Return values
int —table()
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
Return values
void —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 ]) : mixed
Parameters
- $seconds : int
-
Number of seconds
- $countdown : bool = false
-
Show a countdown or not
Return values
mixed —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 $string = null ], int $max, int $padLeft) : string
If an int is passed into $pad_left, then all strings after the first will padded with that many spaces to the left. Useful when printing short descriptions that need to start on an existing line.
Parameters
- $string : string = null
- $max : int
- $padLeft : int
Return values
string —write()
Outputs a string to the cli on it's own line.
public
static write([string $text = '' ][, string $foreground = null ][, string $background = null ]) : mixed
Parameters
- $text : string = ''
-
The text to output
- $foreground : string = null
- $background : string = null
Return values
mixed —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
Return values
void —parseCommandLine()
Parses the command line it was called from and collects all options and valid segments.
protected
static parseCommandLine() : mixed
Return values
mixed —validate()
Validate one prompt "field" at a time
protected
static validate(string $field, string $value, string|array<string|int, mixed> $rules) : bool
Parameters
- $field : string
-
Prompt "field" output
- $value : string
-
Input value
- $rules : string|array<string|int, mixed>
-
Validation rules