Luminova Framework

PHP Luminova: CLI Terminal Helper Class

Last updated: 2026-04-24 22:18:35

A CLI helper class for building interactive command-line tools in NovaKit, with support for input prompts, table output, command execution, and styled messages.

The CLI Terminal class is a command-line helper for Novakit. It handles common CLI tasks such as input, output, formatting, and command execution within the Luminova framework.

It works in both routable Luminova\Base\Command controllers and console-based Luminova\Base\Console controllers.

All methods are static for ease of use. However, some features require initialization. This can be done by calling Terminal::init() or by creating an instance with new Terminal().


Key Features

The Terminal class simplifies CLI development by providing:

  • Table Output – Display data in clean, readable tables.
  • User Prompts – Collect user input, including hidden password input.
  • CLI I/O Helpers – Write to and read from the terminal with ease.
  • Argument Parsing – Extract and work with CLI arguments and flags.
  • Command Execution – Run system commands from your CLI tool.
  • Styled Output – Add colors and formatting for better readability.

Usage

Terminal Initialization

If you use the Terminal class outside command controllers (Luminova\Base\Command or Luminova\Base\Console), you must initialize it manually.

use Luminova\Command\Terminal;

// Initialize terminal support
Terminal::init();

Table Display

Display a simple table with names and emails:

Terminal::table(
    ['Name', 'Email'], 
    [
        ['Name' => 'Peter', 'Email' => '[email protected]'],
        ['Name' => 'Hana', 'Email' => '[email protected]']
    ]
);

Output:

┌───────┬───────────────────┐
│ Name  │ Email             │
├───────┼───────────────────┤
│ Peter │ [email protected] │
├───────┼───────────────────┤
│ Hana  │ [email protected]  │
└───────┴───────────────────┘

Multiple Chooser Prompts

Ask the user to choose an option or default to the first element:

$array = Terminal::chooser(
    'Choose your programming languages?', 
    ['PHP', 'JAVA', 'SWIFT', 'JS', 'SQL', 'CSS', 'HTML']
);

Require the user to choose at least one option is required:

$array = Terminal::chooser(
    'Choose your programming languages?', 
    ['PHP', 'JAVA', 'SWIFT', 'JS', 'SQL', 'CSS', 'HTML'], 
    true
);

User Prompts

Prompt the user with color-coded options and is required:

$color = Terminal::prompt(
    'Are you sure you want to continue?', 
    [
        'green' => 'YES', 
        'red' => 'NO'
    ]
);

Prompt the user to select their gender, without colored text nor validation required:

$gender = Terminal::prompt(
    'What is your gender?', 
    ['male', 'female'], 
    false
);

Prompt the user to select an option with custom validation rules:

$email = Terminal::prompt(
    'Are you sure you want to continue?', 
    ['YES', 'NO'], 
    'required|in_array(YES,NO)'
);

User Input Methods

Request user to enter an input.

$name = Terminal::input('What is your name? ');

Required:

Setting the $default parameter forces user to enter something.

$name = Terminal::input('What is your name? ', default: null);

Request user to enter password without displaying while typing:

$password = Terminal::password('Enter your password? ');

Using prompt to request the user to enter their email address:

$email = Terminal::prompt('What is your email?');

Waiting Examples

Display a waiting message until the user presses any key:

Terminal::waiting();

Show a waiting message for 20 seconds with a countdown:

Terminal::waiting(20);

Show a custom downloading message for 20 seconds:

Terminal::waiting(20, 'Downloading... (%d seconds)');

Freezing Examples

Freeze the console screen for 20 seconds:

Terminal::freeze(20); 

Freeze the console and clear all output and user input for 20 seconds:

Terminal::freeze(20, true);

Progress Bar Examples

Draw a progress bar with with manual step updates:

for ($i = 0; $i <= 100; $i++) {
    $step = Terminal::progress($i, 100);
    usleep(100000);

    if ($step >= 100) {
        echo 'Am done';
        break;
    }
}

Stope a progress bar halfway, up to 50% without completing:

for ($i = 0; $i <= 100; $i++) {
    $step = Terminal::progress($i, 100);
    usleep(100000);

    if ($step >= 50) {
        echo 'Am done halfway';
        break;
    }
}

Watcher Examples

Show 100 lines of progress with callbacks and a beep upon completion:

Terminal::watcher(100, function() {
    Terminal::writeln("Am done here");
}, function(float|int $step) {
    // Avoid adding a new line here to prevent progress bars from miss-aligning except is intended
    Terminal::write(" Current {$step}");
});

Example Output:

index.php command --watch [##########] 100% Current 99 Current 100 Am done here

Animation Example

Draw a spinning animation with an array list of any charters. Animate 5 spins, a 100ms sleep between frames, and a custom completion message:

Terminal::spinner(['-', '\\', '|', '/'], 5, 100000, function() {
    Terminal::write("Finished spinning!\n");
});

Example Output:

index.php foo --spin Animating:

Class Definition

  • Class namespace: Luminova\Command\Terminal

Constants

These constants represent the standard input, output, and error streams, often used in terminal or command-line applications to manage and control where data flows.

ConstantTypeValueDescription
STD_OUTint0Standard output stream, typically used for displaying normal messages or output in a terminal.
STD_ERRint1Standard error stream, used for displaying error messages and diagnostic information.
STD_INint2Standard input stream, used for receiving input from the user or another source in a terminal.

Properties

isReadLine

Is the readline library on the system.

public static bool $isReadLine

Methods

init

Initialize the terminal instance for CLI operations.

  • Sets up standard input/output streams.
  • Detects whether readline extension is available.
  • Checks for color support in the terminal output.

Subsequent calls to this method have no effect once initialization is complete.

public static init(): void

Example:

use Luminova\Command\Terminal;

// Initialize statically
Terminal::init();
Terminal::print("Hello from static init!");

waiting

Displays a countdown timer in the console.

This method shows a countdown with a custom message,or prompts the user to press any key to continue if the timer is 0 or negative.

public static waiting(int $seconds, string $pattern = 'Waiting...(%d seconds)'): void

Parameters:

ParameterTypeDescription
$secondsintThe number of seconds to wait before continuing (default: 0 seconds).
$patternstringA custom message pattern to display during the waiting countdown (default: Waiting...(%d seconds)).
Use %d as a placeholder for the remaining seconds.

Return Value:

Note:

  • The console screen will be cleared during the countdown.
  • If $seconds is less than 1, it displays Press any key to continue... and waits for input.

freeze

Pauses execution for a specified number of seconds, optionally clearing the screen during the freeze.

public static freeze(int $seconds = 10, bool $clear = true): void

Parameters:

ParameterTypeDescription
$secondsintNumber of seconds to pause execution (default: 10).
$clearboolWhether to clear the console screen during the freeze (default: true).

spinner

Displays a rotating spinner animation in the CLI.

The spinner cycles through a set of characters to create a simple loading animation.You can customize the spinner frames, the number of rotations, the speed, andoptionally execute a callback or print "Done!" when finished.

public static spinner(
    array $spinners = [...], 
    int $spins = 10, 
    int $sleep = 100000, 
    \Closure|bool|null $onComplete = null
): void

Parameters:

ParameterTypeDescription
$spinnersarray<int,string>Characters representing each frame of the spinner animation.
(default: : ['-', '\', '|', '/']).
$spinsintNumber of full rotations through the spinner array (default: 10).
$sleepintDelay in microseconds between frames to control animation speed (default: 100_000 = 0.1s).
$onCompletecallable|bool|nullCallback or flag executed after completion.
- If true, prints Done!.
- If a Closure, executes the callback.
- If null, does nothing.

progress

Displays a progress bar in the console for a given step out of a total.

public static progress(int|false $step = 1, int $steps = 10, bool $beep = true): float|int

Parameters:

ParameterTypeDescription
$stepint|falseThe current step in the progress, set to false to indicate completion.
$stepsintThe total number of steps for the progress.
$beepboolWhether to beep when the progress is complete (default: true).

Return Value:

float|int - Return the percentage of completion between (0-100) or 100 if completed.

Note: Progress should be called in a loop otherwise use watcher method.


watcher

Displays a progress bar and executes optional callbacks at each step and upon completion.

Handles iteration internally and provides hooks for progress and finish events.Useful for visual feedback during long-running tasks.

public static watcher(
    int $limit, 
    ?\Closure $onFinish = null, 
    ?\Closure $onProgress = null, 
    bool $beep = true
): void

Parameters:

ParameterTypeDescription
$limitintThe total number of progress steps to display.
$onFinish\Closure|nullA callback to execute when the progress reaches 100% (default: null).
$onProgress\Closure|nullA callback to execute at each progress step (default: null).
$beepboolIndicates whether to emit a beep sound upon completion (default: true).

Progress Callback Signature:

Receiving the current progress percentage using $onProgress Closure.

Terminal::watcher(5, function(float|int $step): void {
    echo "Progress: $step%";
});

Note:This method is designed to be called without a loop, as it handles the iteration internally.It is useful for showing progress while performing a task and executing subsequent actions when complete.


prompt

Prompt the user to type input with optional validation and selectable options.

You can optionally pass an array of options to suggest possible values.Each option can also have a color if supported (e.g., ['green' => 'YES', 'red' => 'NO']).Validation rules can restrict allowed values or be disabled entirely.

public static prompt(
    string $message, 
    array $options = [], 
    string|false|null $validations = null, 
    bool $silent = false
): string

Parameters:

ParameterTypeDescription
$messagestringThe message to prompt.
$optionsarrayOptional array options to prompt for selection.
$validationsstring|false|nullOptional validation rules to ensure only the listed options are allowed (default: null), resulting to validation with rules as required\|in_array(foo,bar,baz).
To disable validation pass false as the value.
$silentboolWhether to print validation failure message if wrong option was selected (default: false).

Return Value:

string - Return the client input value.

See Also:


chooser

Display a multiple-choice selection prompt in the terminal.

Users select options using index numbers. Supports single or multiple selection.

  • If $required is true, at least one option must be selected.
  • $multiChoice allows selecting multiple options separated by commas.
public static chooser(
    string $text, 
    array $options, 
    bool $required = false,  
    bool $multiChoice = true
): array<string|int,mixed>

Parameters:

ParameterTypeDescription
$textstringThe message describing the choice.
$optionsarray<string|int,mixed>The list of selectable options.
Can be indexed or associative array (keys will still be shown as selection indexes).
(e.g, ['male' => 'Male', 'female' => 'Female'] or ['male', 'female']).
$requiredboolWhether the user must select at least one option (default: false).
$multiChoiceboolAllow multiple selections separated by commas (default: true).

Return Value:

array<string|int,mixed> Returns an array of selected keys and their corresponding values.

Throws:


password

Prompt the user to enter a password securely (input hidden).

Works cross-platform:

  • Windows: uses PowerShell or VBS to hide input.
  • Linux/macOS: uses terminal raw input to hide password.

Supports retry attempts, optional empty passwords, and optional timeout.

public static password(
    string $message = 'Enter Password',
    bool $allowEmptyPassword = false,
    int $retry = 3,
    int $timeout = 0
): string

Parameters:

ParameterTypeDescription
$messagestringOptional prompt message (default: Enter Password).
$allowEmptyPasswordboolWhether empty passwords are permitted (default: false).
$retryintNumber of retry attempts, 0 for unlimited (default: 3).
$timeoutintOptional timeout in seconds for input, 0 for no timeout (default: 0).

Return Value:

string - Returns the entered password, or empty string if max retries exceeded.


input

Read a single line of user input from the terminal or piped input.

If $default is null, input is required and the prompt repeats until a value is entered.Supports optional prompts, default values, and a separate STDIN stream handle.For multi-line input, use Luminova\Command\self::read() instead.

public static input(?string $prompt = null, ?string $default = '', bool $newStream = false): string

Parameters:

ParameterTypeDescription
$promptstring|nullOptional message displayed before reading input.
$defaultstring|nullDefault value returned if input is empty. Null = required input.
$newStreamboolOpen a new STDIN stream as a separate handle (default: false).

Return Value:

string - Returns the trimmed input string or the default value.


read

Read input from STDIN, supporting single or multi-line input.

Suitable for piped data or long content. For interactive prompts or single-line input,use Luminova\Command\self::input() instead.

When $eof is true, the entire STDIN stream is read until EOF.When $eof is false, a single line is read.

Alias Luminova\Command\self::readInput()

public static read(string $default = '', bool $eof = true, bool $newStream = false): string

Parameters:

ParameterTypeDescription
$defaultstringDefault value returned if reading fails or input is empty.
$eofboolRead until EOF if true, otherwise single line (delegates to Luminova\Command\self::input()).
$newStreamboolOpen a new STDIN stream as a separate handle (default: false).

Return Value:

string - Returns trimmed input string or default if empty/failure.

Example:

Read From Pipe Input:

echo "Log Message From Pipe" | php index.php logger
php index.php list-something | php index.php logger

tablist

Displays a selectable list in the terminal with keyboard navigation.

Users can navigate the options using:

  • Arrow keys (up/down)
  • Tab / Shift+Tab
  • Enter to select
  • Escape to cancel (returns empty string)
  • Ctrl+C to exit

The selected option is returned as a string. Supports optional placeholder text,foreground and background colors for the highlighted selection, and clearing the screen after selection.

public static tablist(
    array $options, 
    int $default = 0,
    ?string $placeholder = null,
    bool $clearOnSelect = true,
    string $foreground = 'green', 
    ?string $background = null
): string

Parameters:

ParameterTypeDescription
$optionsarray<int,string|int>The list of selectable options.
$defaultintThe default selected index (0-based).
$placeholderstring|nullOptional placeholder text to display above the list (default: null).
$clearOnSelectboolWhether to clear the terminal after selection (default: true).
$foregroundstringForeground color for the highlighted option (default: green).
$backgroundstring|nullOptional background color for the highlighted option.

Return Value:

string - Returns the selected option as a string, or empty string if cancelled.


table

Generate and print a formatted table structure to the console.

Each row is an associative array where the keys match the column headers.Supports optional text coloring for headers, body, and borders, as well as controllingwhether borders are shown and whether newlines within cells are retained.

public static table(
    string[] $headers, 
    array<int,array<string,string>> $rows, 
    ?string $foreground = null,
    ?string $headerColor = null, 
    ?string $borderColor = null,
    bool $border = true
): string

Parameters:

ParameterTypeDescription
$headersarray<int,string>Column headers for the table.
$rowsarray<int,array<string,string>>Table rows where each row is an associative array
with keys matching headers.
$foregroundstring|nullOptional text color for table body (default: null).
$headerColorstring|nullOptional text color for table headers (default: null).
$borderColorstring|nullOptional text color for table borders (default: null).
$borderboolWhether to display borders between rows and columns (default: true).
$shouldRetainNewlinesboolWhether to keep newlines inside cells (default: false).

Return Value:

string - Returns the formatted table as a string, ready for console output.


error

Display an error message box in the console.

The message is formatted as a block with a default red background and white text.

public static error(
    string $text,
    ?string $foreground = 'white',
    ?string $background = 'red',
    ?int $width = null
): void

Parameters:

ParameterTypeDescription
$textstringThe error message to display.
$foregroundstring|nullOptional text color (default: white).
$backgroundstring|nullOptional background color (default: red).
$widthint|nullOptional width of the block (default: auto).

success

Display a success message box in the console.

The message is formatted as a block with a default green background and white text.

public static success(
    string $text,
    ?string $foreground = 'white',
    ?string $background = 'green',
    ?int $width = null
): void

Parameters:

ParameterTypeDescription
$textstringThe success message to display.
$foregroundstring|nullOptional text color (default: white).
$backgroundstring|nullOptional background color (default: green).
$widthint|nullOptional width of the block (default: auto).

info

Display an informational message in the console.

By default, the text is displayed with a blue foreground and no background.

public static info(
    string $text,
    ?string $foreground = 'blue',
    ?string $background = null,
    ?int $width = null
): void

Parameters:

ParameterTypeDescription
$textstringThe message to display.
$foregroundstring|nullOptional foreground color (default: blue).
$backgroundstring|nullOptional background color (default: none).
$widthint|nullOptional width of the block (default: auto).

writeln

Print text followed by a newline to the specified stream (default: STDOUT).

Supports optional foreground and background colors.

public static writeln(
    string $text = '',
    ?string $foreground = null,
    ?string $background = null,
    int $stream = self::STD_OUT
): void

Parameters:

ParameterTypeDescription
$textstringThe text to write.
$foregroundstring|nullOptional foreground color.
$backgroundstring|nullOptional background color.
$streamintStream resource to write to
(e.g, Terminal::STD_OUT, Terminal::STD_IN, Terminal::STD_ERR).

write

Print text without a newline to the specified stream (default: STDOUT).

Supports optional foreground and background colors.

public static write(
    string $text = '',
    ?string $foreground = null,
    ?string $background = null,
    int $stream = self::STD_OUT
): void

Parameters:

ParameterTypeDescription
$textstringThe text to write.
$foregroundstring|nullOptional foreground color.
$backgroundstring|nullOptional background color.
$streamintStream resource to write to
(e.g, Terminal::STD_OUT, Terminal::STD_IN, Terminal::STD_ERR).

print

Print text directly to the console using echo.

Optional colors can be applied for foreground and background.

public static print(string $text, ?string $foreground = null, ?string $background = null): void

Parameters:

ParameterTypeDescription
$textstringThe text to print.
$foregroundstring|nullOptional foreground color.
$backgroundstring|nullOptional background color.

fwrite

Write text directly to a stream resource without applying colors.

Falls back to echo if the environment is non-command-based.

public static fwrite(string $text, resource|int $handler = self::STD_OUT): void

Parameters:

ParameterTypeDescription
$textstringThe text to write.
$handlerresource|intStream resource (STDOUT, STDERR, STDIN, or custom).

about

Displays system and environment information in a table format.

Intended for CLI usage, this method outputs details such as PHP version, operating system, terminal size, and other runtime-related information.

public static about(): void

header

Prints the NovaKit CLI header banner.

Displays framework version, CLI tool version, and current server time.The header is skipped if the --no-header argument is present.

public static header(): bool

Return Value:

bool - Returns true if the header was printed, false if suppressed.


whoami

Returns the system user executing the current script.

Attempts to resolve the actual OS-level user using a shell command.If unavailable, falls back to PHP's process user.

public static whoami(): string

Return Value:

string - Return the current system username with whitespace removed.


whichPhp

Detect the PHP CLI executable path.

This method attempts to locate a working PHP CLI binary using multiple strategies:

  1. The PHP_BINARY constant (the currently running PHP binary).
  2. The which php shell command (Linux/macOS).
  3. Common default PHP paths for Linux, macOS, and Windows environments.

When $test is true, each candidate is verified by running php -v to ensure it is functional.

public static whichPhp(bool $test = true): ?string

Parameters:

ParameterTypeDescription
$testboolIf true, test each candidate binary to ensure it runs (default: true).

Return Value:

string|null - Return the full path to a usable PHP CLI executable, or null if none could be detected.


terminate

Terminates script execution immediately, optionally displaying a message and providing an exit code.

public static terminate(?string $message = null, int $exitCode = STATUS_SUCCESS): never

Parameters:

ParameterTypeDescription
$messagestring|nullOptional message to display before exiting.
$exitCodeintExit status code (default: STATUS_SUCCESS).

timeout

Executes a callback function if no activity is detected on the specified stream within a timeout.

public static timeout(\Closure $callback, int $timeout = 0, resource|string|int $stream = self::STD_IN): bool

Parameters:

ParameterTypeDescription
$callback\ClosureCallback function to execute on timeout.
$timeoutintTimeout in seconds. If <= 0, the callback is executed immediately (default: 0).
$streamresource|string|intOptional stream to monitor for activity (default: STDIN).

Return Value:

bool - Returns true if the timeout occurred and the callback was executed, false otherwise.


execute

Execute a system command and return its output as an array of lines.

public static execute(string $command): array|false

Parameters:

ParameterTypeDescription
$commandstringThe command to execute.

Return Value:

array|false - Returns the output lines of the command on success, or false on failure.


beeps

Emits a beep (bell) sound in the terminal a specified number of times.

Useful for notifications, alerts, or signaling the user in CLI scripts.

public static beeps(int $total = 1): void

Parameters:

ParameterTypeDescription
$totalintNumber of times to beep (default: 1).

oops

Display an error message for an unknown command.

Prints a formatted command not found message to STDERR.

public static oops(string $command, ?string $color = 'red'): int

Parameters:

ParameterTypeDescription
$commandstringThe executed command.
$colorstring|nullOptional text color for the command name (default: red).

Return Value:

int - Always returns STATUS_ERROR.


Highlights a URL in the terminal to indicate it is clickable.

If ANSI hyperlinks are supported, the URL will be clickable. Otherwise, it will be underlined.

public static link(string $url, ?string $title = null): void

Parameters:

ParameterTypeDescription
$urlstringThe URL to highlight.
$titlestring|nullOptional title to display instead of the URL (default: null).

visibility

Show or hide user input in the terminal.

Useful for password prompts or sensitive input.

public static visibility(bool $visibility = true): bool

Parameters:

ParameterTypeDescription
$visibilityboolTrue to show input, false to hide it.

Return Value:

bool - Returns true on success, false on failure.


clear

Clear the terminal screen.

Supported modes:

  • default: Clear the entire screen.
  • partial: Clear from cursor to bottom.
  • full: Clear screen and scroll-back buffer.
public static clear(string $mode = 'default'): void

Parameters:

ParameterTypeDescription
$modestringClearing mode (default: "default").

flush

Remove the last printed line(s) from the terminal output.

If no output is provided, clears the previous line.If output is provided, clears the exact number of wrapped lines.

public static flush(?string $lastOutput = null): void

Parameters:

ParameterTypeDescription
$lastOutputstring|nullPreviously printed output (optional).

validate

Validate user input against a set of rules, typically used for prompts.

public static validate(string $value, array $rules): bool

Parameters:

ParameterTypeDescription
$valuestringThe input value to validate.
$rulesarrayValidation rules to apply (e.g., required&amp;#124;in_array([yes,no])).

Return Value:

bool - Returns true if validation passes, false otherwise.


escape

Escape a command-line argument to ensure it is safely executed in the shell.

Handles special characters differently for Windows and Unix-like platforms.

public static escape(?string $argument): string

Parameters:

ParameterTypeDescription
$argumentstring|nullThe argument to escape.

Return Value:

string - Returns the safely escaped string ready for shell execution.

Example:

$argument = 'example argument with "special" characters & symbols';
$escaped = Terminal::escape($argument);

Terminal::exec("echo $escaped", $output);

print_r($output);

replace

Replace placeholders in a command string with values from an environment array.

Placeholders must follow the format ${:VAR_NAME}, where VAR_NAME corresponds to a key in $env.Optionally, replacements can be escaped for safe shell execution.

public static replace(string $command, array&lt;string,mixed&gt; $env, bool $escape = false): string

Parameters:

ParameterTypeDescription
$commandstringThe command containing placeholders (e.g., echo ${:USER}).
$envarray<string,mixed>Associative array mapping placeholder names to values.
$escapeboolWhether to escape each replacement for shell safety (default: false).

Return Value:

string - Returns the command with all placeholders replaced.

Throws:

Example:

Example of the environment variables:

$command = 'echo "${:USER} is running a ${:TASK}"';
$env = [
    'USER' => 'Alice',
    'TASK' => 'test command'
];

Replace placeholders:

$command = Terminal::replace($command, $env);
echo $command; 
// Output: echo "Alice is running a test command"

Execute the command:

Terminal::exec($escaped, $output);
print_r($output);

cursorVisibility

Controls the cursor visibility in the terminal.

public static cursorVisibility(bool $showCursor): void

Parameters:

ParameterTypeDescription
$showCursorboolSet to true to show the cursor, false to hide it.

newLine

Print new lines based on specified count.

public static newLine(int $count = 1): void

Parameters:

ParameterTypeDescription
$countintThe number of new lines to print.

isStreamSupports

Checks whether the current stream resource supports or refers to a valid terminal type device.

public static isStreamSupports(string $function, resource|string|int $resource = self::STD_OUT): bool

Parameters:

ParameterTypeDescription
$functionstringFunction name to check.
$resourceresource|string|intResource to handle (e.g. Terminal::STD_*, STDIN, STDOUT).

Return Value:

bool - Return true if stream resource is supported, otherwise false.


getWidth

Attempts to determine the width of the viewable command line window.

final public static getWidth(int $default = 80): int

Parameters:

ParameterTypeDescription
$defaultintOptional default width (default: 80).

Return Value:

int - Return terminal window width or default.


getHeight

Attempts to determine the height of the viewable command line window.

final public static getHeight(int $default = 24): int