Command Features

Colors

The SigmaPHP-Console library provides built-in color and text formatting support through ANSI escape sequences. You can apply colors directly to terminal output when writing messages from your console commands, making it easier to distinguish messages and improve readability.

Foreground Colors

The library supports the following ANSI-16 foreground colors, which can be specified using their corresponding string names:

Color ANSI Code
default39
black30
red31
green32
yellow33
blue34
magenta35
cyan36
light_gray37
dark_gray90
light_red91
light_green92
light_yellow93
light_blue94
light_magenta95
light_cyan96
white97

Background Colors

The library also supports ANSI-16 background colors. These can be applied using the bg formatting option when writing command output.

Color ANSI Code
default49
black40
red41
green42
yellow43
blue44
magenta45
cyan46
light_gray47
dark_gray100
light_red101
light_green102
light_yellow103
light_blue104
light_magenta105
light_cyan106
white107

ANSI-256 Colors

In addition to the standard ANSI-16 palette, SigmaPHP-Console supports ANSI-256 colors, providing access to an extended range of terminal colors.

Unlike ANSI-16 colors, ANSI-256 colors are specified using integer values instead of string names. For example, you can use 180 to set an ANSI-256 background color.

Using Colors in a Command

You can apply colors and text formatting directly when writing terminal output using the write(), writeln(), and writeErr() methods.

Formatting options are passed as a semicolon-separated string, allowing you to combine foreground colors, background colors, and text styles in a single declaration.


$this->write('Hello World', 'fg=red;bg=180;bold');
    

The formatting options in this example are:

Multiple formatting options can be combined using semicolons, giving you complete control over how terminal messages are displayed.

Text Formatting

The SigmaPHP-Console library supports text formatting through ANSI escape sequences. You can combine different text styles with foreground and background colors to customize terminal output and make command messages more readable and expressive.

Available Text Styles

The following text formatting styles are supported:

Style ANSI Code Description
bold 1 Displays text in bold.
dim 2 Displays text with reduced intensity.
underline 4 Underlines the text.
blink 5 Makes the text blink when supported by the terminal.
reverse 7 Reverses the foreground and background colors.
hidden 8 Hides the text when supported by the terminal.

Using Text Formatting in a Command

Text styles can be applied directly to command output using the write() method. Simply pass the desired formatting style as the second argument.


$this->write('Hello World', 'bold');
    

You can also combine multiple formatting styles by separating them with semicolons.


$this->write('Important Message', 'bold;underline');
    

Combining Text Styles and Colors

Text formatting can be combined with foreground and background colors in the same declaration. This allows you to create distinctive output for different types of command messages.


$this->write('Warning', 'fg=yellow;bold');

$this->write('Error', 'fg=red;bold;underline');

$this->write('Success', 'fg=green;bold');
    

Background colors can also be included alongside text styles and foreground colors:


$this->write('Important', 'fg=white;bg=red;bold');
    

For more flexibility, you can also use ANSI-256 colors when specifying foreground or background colors. Unlike ANSI-16 colors, ANSI-256 colors are specified using integer values instead of color names.

The following example combines an ANSI-256 background color with foreground coloring and bold formatting:


$this->write('Highlighted', 'fg=white;bg=180;bold');
    

By combining text styles and colors, you can produce clear, expressive, and well-organized terminal output while keeping formatting declarations simple and close to the messages they affect.

Boxes

The Box class provides a simple way to display text inside a bordered box in the terminal. It is useful for highlighting messages, presenting important information, or visually separating sections of command output.

Creating a Box

The create() method accepts the text to display, an optional formatting style, and an optional border character.

Parameters:

Parameter Type Default Description
$text string Required The text to display inside the box.
$style string '' Formatting styles and colors to apply to the box.
$border string '*' The character used to draw the box border.

Using a Box in a Command

The Box class is accessible directly from a command through the $this->box property. You can use it to display a message inside a bordered box with a single method call.


$this->box->create("Hello, World!");
    

This produces the following terminal output:

***********************************
*                                 *
*         Hello, World!           *
*                                 *
***********************************

Custom Borders

You can customize the appearance of the box by providing a different border character as the third argument.


$this->box->create("Hello, World!", '', '#');
    

The following example uses # instead of the default * character:

###################################
#                                 #
#         Hello, World!           #
#                                 #
###################################

Styling the Box

The $style parameter allows you to apply colors and text formatting to the box. You can combine multiple formatting options using semicolons.


$this->box->create("Hello, World!", 'fg=green;bold');
    

This example applies green foreground coloring and bold formatting to the box output.

Tables

The Table class provides a convenient way to display structured data in formatted terminal tables. It is useful for presenting lists, records, and other tabular information in a clear and organized layout.

Creating a Table

The create() method accepts an array of column headers, an array containing the table rows, and an optional formatting style.

Parameters:

Parameter Type Default Description
$header array<string> Required An array containing the table column headers.
$data array<array<string>> Required An array containing the table rows and their values.
$style string '' Formatting styles and colors to apply to the table.

Using a Table in a Command

The Table class is accessible directly from a command through the $this->table property. Pass the column headers as the first argument and the table rows as the second.


$this->table->create(
    ['Name', 'Age', 'City'],
    [
        ['John', '25', 'Dubai'],
        ['Sarah', '30', 'New York'],
        ['Mike', '28', 'Tokyo'],
    ]
);
    

This produces a formatted table similar to the following:

--------------------------
| Name  | Age | City     |
--------------------------
| John  | 25  | Dubai    |
| Sarah | 30  | New York |
| Mike  | 28  | Tokyo    |
--------------------------

Styling the Table

The optional $style parameter allows you to customize the table output using foreground colors, background colors, and text formatting options.


$this->table->create(
    [...],
    'fg=blue;bg=green'
);
    

Multiple formatting options can be combined using semicolons, allowing you to customize the appearance of your terminal tables consistently with the rest of your command output.

Questions

The Question service provides a convenient way to interact with users through questions and prompts directly within console commands. It supports confirmations, text input, predefined choices, and hidden input for sensitive information.

The question service is accessible directly through the command's $this->question property.

Available Methods

The following methods are available:

Method Parameters Return Type Description
confirmation() $message bool Asks the user to confirm an action.
ask() $question string Prompts the user for text input.
choice() $question, $options string Allows the user to select an option from a list.
secret() $question string Prompts the user for hidden input.

Confirmation

The confirmation() method asks the user to confirm an action and returns a boolean indicating whether the action was confirmed.

The method accepts the following case-insensitive responses:

Both uppercase and lowercase inputs are accepted, including YES, Yes, Y, NO, and n.


$input = $this->question->confirmation("Please confirm?");
    

The method returns:

Asking a Question

The ask() method prompts the user for text input and returns the entered value as a string. It is useful for collecting names, descriptions, or other information during command execution.


$input = $this->question->ask("What's your name?");
    

Choice

The choice() method allows the user to select a value from a predefined list of available options.

It accepts the question as its first argument and an array of string options as its second argument. The selected value is returned as a string.


$input = $this->question->choice(
    "What's your favorite color?",
    ['red', 'blue', 'green']
);
    

Secret Input

The secret() method prompts the user for sensitive information without displaying the entered characters in the terminal. This is particularly useful for collecting passwords, tokens, or other confidential values.


$input = $this->question->secret("Enter your password:");
    

Progress Bar

The ProgressBar utility provides a convenient way to visualize the progress of long-running operations in the console. It displays completed and remaining steps using a customizable progress indicator.

You can customize its appearance using different border characters, progress symbols, colors, and text formatting styles.

Creating a Progress Bar

Create a progress bar inside a command using the createProgressBar() method.


$progressBar = $this->createProgressBar();
    

The method accepts the following parameters:

Parameter Type Default Description
$leftBorder string [ The character or text used for the left border.
$rightBorder string ] The character or text used for the right border.
$inProgressSymbol string - The symbol used to represent incomplete progress.
$completeSymbol string = The symbol used to represent completed progress.
$style string '' Formatting styles and colors to apply to the progress bar.

Using a Progress Bar

Once created, the progress bar can be used to track the execution of an operation. Start it by specifying the total number of steps, update it as work is completed, and call end() when the operation finishes.


$progressBar = $this->createProgressBar();

$items = 100;

$progressBar->start($items);

for ($i = 0; $i < $items; $i++) {
    // Process the item.

    $progressBar->update(1);
}

$progressBar->end();
    

Starting a Progress Bar

Use the start() method to initialize the progress bar. It accepts the total number of steps and an optional starting position.


$items = 10;

$progressBar->start($items);
    

The method accepts the following parameters:

Updating the Progress

Use the update() method to advance the progress bar as individual tasks or processing steps are completed.


for ($i = 0; $i < $items; $i++) {
    $progressBar->update(1);
}
    

The $steps parameter specifies how many steps to advance the progress bar. You can provide a value greater than 1 when multiple steps are completed at once.

Ending a Progress Bar

Once the operation is complete, call the end() method to finalize the progress bar and complete its terminal output.


$progressBar->end();
    

Customizing the Progress Bar

You can customize the progress bar's appearance when creating it by providing custom border characters, progress symbols, and formatting styles.


$progressBar = $this->createProgressBar(
    '<',
    '>',
    '.',
    '#',
    'fg=light_green'
);
    

This allows you to adapt the progress indicator to match the visual style of your command output.

Loading Spinner

The LoadingSpinner utility provides an animated indicator for long-running operations where displaying a numerical progress percentage is not necessary.

Unlike a progress bar, a loading spinner continuously displays an animation while an operation is running, providing visual feedback that the command is still processing.

Creating a Loading Spinner

Create a loading spinner inside a command using the createLoadingSpinner() method.


$spinner = $this->createLoadingSpinner();
    

The method accepts an optional animation pattern and formatting style.

Parameter Type Default Description
$pattern string frames The animation pattern used by the spinner.
$style string '' Formatting styles and colors to apply to the spinner.

Spinner Patterns

SigmaPHP-Console provides several built-in animation patterns that can be selected when creating a loading spinner.

Pattern Animation
arc ◜ ◝ ◞ ◟
frames | / - \
dots . .. ...
sweep *---- -*--- --*-- ---*- ----*
pipes ┤ ┘ ┴ └ ├ ┌ ┬ ┐
braille ⠋ ⠙ ⠹ ⠸ ⠼ ⠴ ⠦ ⠧ ⠇ ⠏
brackets [ ] [=] [==] [===] [ ==] [ =] [ ]

The default animation pattern is frames. You can select a different pattern by passing its name to the creation method.


$spinner = $this->createLoadingSpinner('dots');
    

Running a Loading Spinner

Use the run() method to execute an operation while displaying the loading animation. The method accepts a callback containing the operation to perform.


$spinner = $this->createLoadingSpinner('dots');

$spinner->run(function () {
    // Perform a long-running operation.
});
    

The callback executes while the spinner is running. Once the callback completes, the spinner stops and its output is finalized.

The run() method accepts the following parameter:

Parameter Type Description
$callback callable The operation to execute while the spinner is running.

Custom Spinner Style

You can customize the spinner's appearance by providing a formatting style when creating it. The style supports the same foreground colors, background colors, and text formatting options available throughout the console library.


$spinner = $this->createLoadingSpinner(
    'dots',
    'fg=white;bg=red;bold'
);
    

Platform Support

The loading spinner currently relies on the PHP pcntl extension to run its animation while the callback is executing. Consequently, this feature is supported on UNIX-like operating systems only.

Windows is currently not supported because the pcntl extension is unavailable on that platform.

An alternative implementation using the PHP parallel extension may be considered in the future. However, at the time of writing, the extension is not considered mature enough to replace the current implementation.

↑ Back to top