PHP Luminova: Terminal I/O Utilities
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\Cli\AbstractController controllers and console-based Luminova\Base\Cli\AbstractConsole controllers.
All methods are static for ease of use. However, some features require initialization. Call Terminal::init() before using those features.
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\Cli\AbstractController or Luminova\Base\Cli\AbstractConsole), you must initialize it manually.
use Luminova\Command\Terminal;
// Initialize terminal support
Terminal::init();Table Display
Display a simple table with names and emails:
echo Terminal::table([
['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:
$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,
static function (): void { Terminal::writeln("Finished"); },
// Avoid adding a new line here to prevent progress bars
// from miss-aligning except is intended
static function (float|int $step): void { Terminal::write(" Current {$step}"); });Example Output:
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,
0.1, static function (): void { Terminal::write("Finished spinning!\n"); });Example Output:
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.
| Constant | Type | Value | Description |
|---|---|---|---|
STD_OUT | int | 1 | Standard output stream, typically used for displaying normal messages or output in a terminal. |
STD_ERR | int | 2 | Standard error stream, used for displaying error messages and diagnostic information. |
STD_IN | int | 0 | Standard 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 = false;Methods
init
Initialize the terminal instance for CLI operations.
- Sets up standard input/output streams.
- Detects whether
readlineextension is available. - Checks for color support in the terminal output.
Subsequent calls to this method have no effect once initialization is complete.
public static function init(): voidExample:
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 function waiting(
int $seconds = 0,
string $pattern = 'Waiting...(%d seconds)'
): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$seconds | int | Number of seconds to wait before continuing (default: 0). |
$pattern | string | Message pattern displayed during the countdown (default: 'Waiting...(%d seconds)'). Use '%d' as a placeholder for the remaining seconds. |
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 function freeze(float|int $seconds = 1, bool $clear = true): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$seconds | float|int | Number of seconds to pause execution (default: 1). |
$clear | bool | Whether 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 function spinner(
array $spinners = ['-', '\\', '|', '/'],
int $spins = 10,
float|int $sleep = 0.1,
Closure|bool|null $onComplete = null
): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$spinners | array<int,string> | Characters representing each frame of the spinner animation. Default: ['-', '\', '|', '/']. |
$spins | int | Number of full rotations through the spinner array (default: 10). |
$sleep | float|int | Delay in seconds between frames to control animation speed (default: 0.1s). |
$onComplete | Closure|bool|null | Callback or flag executed after completion. - If true, prints "Done!\n". - 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 function progress(
int|bool $step = 1,
int $steps = 10,
bool $beep = true
): float|intParameters:
| Parameter | Type | Description |
|---|---|---|
$step | int|bool | Current step of the progress (1-based). Set to false to mark completion. |
$steps | int | Total number of steps for the progress (default: 10). |
$beep | bool | Whether to beep when progress completes (default: true). |
Return:
float|int - Returns the completion percentage (0-100). Returns 100 if completed.
Note:Progress should be called in a loop otherwise use
watchermethod.
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 function watcher(
int $limit,
?Closure $onFinish = null,
?Closure $onProgress = null,
bool $beep = true
): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$limit | int | Total number of progress steps. |
$onFinish | Closure|null | Optional callback executed once when progress reaches 100%. |
$onProgress | Closure|null | Optional callback executed on each progress step with the current percentage. |
$beep | bool | Whether to emit a beep upon completion (default: true). |
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 function prompt(
string $message,
array $options = [],
string|bool|null $validations = null,
bool $silent = false
): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$message | string | The message to prompt the user with. |
$options | array<string|int,string|int> | Optional list of suggested options. |
$validations | string|bool|null | Optional validation rules: - null (default): automatically uses required|in_array(options) - false: disables validation - string: custom validation rules |
$silent | bool | Whether to suppress validation failure messages (default: false) |
Return:
string - Returns the user's input after validation.
chooser
Display a multiple-choice selection prompt in the terminal.
Users select options using index numbers. Supports single or multiple selection.
- If
$requiredis true, at least one option must be selected. $multiChoiceallows selecting multiple options separated by commas.
public static function chooser(
string $text,
array $options,
bool $isRequired = false,
bool $allowMultiChoice = true
): arrayParameters:
| Parameter | Type | Description |
|---|---|---|
$text | string | The message describing the choice. |
$options | array<string|int,mixed> | The list of selectable options. Can be indexed or associative array (keys will still be shown as selection indexes). |
$isRequired | bool | Whether the user must select at least one option (default: false). |
$allowMultiChoice | bool | Allow multiple selections separated by commas (default: true). |
Return:
array<string|int,mixed> - Returns an array of selected keys and their corresponding values.
Throws:
- Luminova\Exceptions\IOException - If
$optionsis empty or invalid.
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 function password(
string $message = 'Enter Password',
bool $allowEmptyPassword = false,
int $retry = 3,
int $timeout = 0
): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$message | string | Optional prompt message (default: 'Enter Password'). |
$allowEmptyPassword | bool | Whether empty passwords are permitted (default: false). |
$retry | int | Number of retry attempts, 0 for unlimited (default: 3). |
$timeout | int | Optional timeout in seconds for input, 0 for no timeout (default: 0). |
Return:
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 function input(
?string $prompt = null,
?string $default = '',
bool $newStream = false
): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$prompt | ?string | Optional message displayed before reading input. |
$default | ?string | Default value returned if input is empty. Null = required input. |
$newStream | bool | Open a new STDIN stream as a separate handle (default: false). |
Return:
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 function read(string $default = '', bool $eof = true, bool $newStream = false): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$default | string | Default value returned if reading fails or input is empty. |
$eof | bool | Read until EOF if true, otherwise a single line. |
$newStream | bool | Open a new STDIN stream as a separate handle (default: false). |
Return:
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 dump | php index.php loggertablist
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 function tablist(
array $options,
int $default = 0,
?string $placeholder = null,
bool $clearOnSelect = true,
string $foreground = 'green',
?string $background = null
): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$options | array<int,string|int> | The list of selectable options. |
$default | int | The default selected index (0-based). |
$placeholder | ?string | Optional placeholder text to display above the list (default: null). |
$clearOnSelect | bool | Whether to clear the terminal after selection (default: true). |
$foreground | string | Foreground color for the highlighted option (default: 'green'). |
$background | ?string | Optional background color for the highlighted option. |
Return:
string - Returns the selected option as a string, or empty string if cancelled.
table
Generate a formatted table from associative array rows.
public static function table(
array $data,
?string $foreground = null,
?string $headerColor = null,
?string $borderColor = null,
bool $tableBorder = true,
bool $shouldRetainNewlines = false
): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$data | array<int,array<string, string>> | Table data, where each row is an associative array of column names and cell values. |
$foreground | ?string | Optional text color for table body (default: null). |
$headerColor | ?string | Optional text color for column headers (default: null). |
$borderColor | ?string | Optional text color for table borders (default: null). |
$tableBorder | bool | Whether to display separators between data rows (default: true). |
$shouldRetainNewlines | bool | Whether to preserve line breaks within cell content instead of joining wrapped lines (default: false). |
Return:
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 function error(
string $text,
?string $foreground = 'white',
?string $background = 'red',
?int $width = null
): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$text | string | The error message to display. |
$foreground | ?string | Optional text color (default: white). |
$background | ?string | Optional background color (default: red). |
$width | ?int | Optional 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 function success(
string $text,
?string $foreground = 'white',
?string $background = 'green',
?int $width = null
): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$text | string | The success message to display. |
$foreground | ?string | Optional text color (default: white). |
$background | ?string | Optional background color (default: green). |
$width | ?int | Optional 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 function info(
string $text,
?string $foreground = 'blue',
?string $background = 'cyan',
?int $width = null
): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$text | string | The message to display. |
$foreground | ?string | Optional foreground color (default: blue). |
$background | ?string | Optional background color (default: none). |
$width | ?int | Optional 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 function writeln(
string $text = '',
?string $foreground = null,
?string $background = null,
int $stream = self::STD_OUT,
bool $closeHandler = true
): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$text | string | The text to write. |
$foreground | ?string | Optional foreground color name. |
$background | ?string | Optional background color name. |
$stream | int | Target stream or stream identifier (e.g. Terminal::STD_OUT, STDERR, or custom resource). |
$closeHandler | bool | Whether to close non-standard streams after writing. |
write
Print text without a newline to the specified stream (default: STDOUT).
Supports optional foreground and background colors.
public static function write(
string $text = '',
?string $foreground = null,
?string $background = null,
int $stream = self::STD_OUT,
bool $closeHandler = true
): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$text | string | The text to write. |
$foreground | ?string | Optional foreground color name. |
$background | ?string | Optional background color name. |
$stream | int | Target stream or stream identifier. |
$closeHandler | bool | Whether to close non-standard streams after writing. |
Print text directly to the console using echo.
Optional colors can be applied for foreground and background.
public static function print(
string $text,
?string $foreground = null,
?string $background = null
): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$text | string | The text to print. |
$foreground | ?string | Optional foreground color name. |
$background | ?string | Optional background color name. |
fwrite
Write text directly to a stream resource without applying colors.
Falls back to echo if the environment is non-command-based.
public static function fwrite(string $text, mixed $handler = self::STD_OUT, bool $closeHandler = true): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$text | string | The text to write. |
$handler | mixed | Stream identifier, resource, or path. |
$closeHandler | bool | Whether to close non-standard streams after writing. |
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 function about(): voidheader
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 function header(): boolReturn:
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 function whoami(): stringReturn:
string - 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:
- The
PHP_BINARYconstant (the currently running PHP binary). - The
which phpshell command (Linux/macOS). - Common default PHP paths for Linux, macOS, and Windows environments.
When $verify is true, each candidate is verified by running php -v to ensure it is functional.
public static function whichPhp(?string $version = null, bool $verify = true): ?stringParameters:
| Parameter | Type | Description |
|---|---|---|
$version | ?string | PHP version hint for binary lookup. |
$verify | bool | If true, test each candidate binary to ensure it runs (default: true). |
Return:
string|null - 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 function terminate(?string $message = null, int $exitCode = STATUS_SUCCESS): neverParameters:
| Parameter | Type | Description |
|---|---|---|
$message | ?string | Optional message to display before exiting. |
$exitCode | int | Exit status code (default: STATUS_SUCCESS). |
Return:
never - Terminates the process.
timeout
Executes a callback function if no activity is detected on the specified stream within a timeout.
public static function timeout(Closure $callback, int $timeout = 0, mixed $stream = self::STD_IN): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$callback | Closure | Callback function to execute on timeout. |
$timeout | int | Timeout in seconds. If <= 0, the callback is executed immediately (default: 0). |
$stream | resource|string|int | Optional stream to monitor for activity (default: STDIN). |
Return:
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 function execute(string $command): array|boolParameters:
| Parameter | Type | Description |
|---|---|---|
$command | string | The command to execute. |
Return:
string[]|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 function beeps(int $total = 1): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$total | int | Number 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 function oops(string $command, ?string $color = 'red'): intParameters:
| Parameter | Type | Description |
|---|---|---|
$command | string | The executed command. |
$color | ?string | Optional text color for the command name (default: red). |
Return:
int - Always returns STATUS_ERROR.
link
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 function link(string $url, ?string $title = null): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$url | string | The URL to highlight. |
$title | ?string | Optional 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 function visibility(bool $visibility = true): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$visibility | bool | True to show input, false to hide it. |
Return:
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 function clear(string $mode = 'default'): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$mode | string | Clearing 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 function flush(?string $lastOutput = null): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$lastOutput | ?string | Previously printed output (optional). |
validate
Validate user input against a set of rules, typically used for prompts.
public static function validate(string $value, array $rules, array $messages = []): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$value | string | The input value to validate. |
$rules | array<string, string> | Validation rules to apply (e.g., required|in_array([yes,no])). |
$messages | array<string, string> | Validation error messages. |
Return:
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 function escape(?string $argument): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$argument | ?string | The argument to escape. |
Return:
string - Returns the safely escaped string ready for shell execution.
Example:
$argument = 'example argument with "special" characters & symbols';
$escaped = Terminal::escape($argument);
$output = Terminal::execute("echo $escaped");
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 function replace(string $command, array $env, bool $escape = false): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$command | string | The command containing placeholders (e.g., echo ${:USER}). |
$env | array<string,mixed> | Associative array mapping placeholder names to values. |
$escape | bool | Whether to escape each replacement for shell safety (default: false). |
Return:
string - Returns the command with all placeholders replaced.
Throws:
- Luminova\Exceptions\IOException - If a placeholder has no corresponding key in
$env.
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:
$command = 'echo ${:USER}';
$escaped = Terminal::replace($command, $env, escape: true);
$output = Terminal::execute($escaped);
print_r($output);cursorVisibility
Controls the cursor visibility in the terminal.
public static function cursorVisibility(bool $showCursor): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$showCursor | bool | Set to true to show the cursor, false to hide it. |
newLine
Print new lines based on specified count.
public static function newLine(int $count = 1): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$count | int | The number of new lines to print. |
isStreamSupports
Checks whether the current stream resource supports or refers to a valid terminal type device.
public static function isStreamSupports(string $function, mixed $resource = self::STD_OUT): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$function | string | Function name to check. |
$resource | resource|string|int | Resource to handle (e.g. Terminal::STD_*, STDIN, STDOUT). |
Return:
bool - Return true if stream resource is supported, otherwise false.
getWidth
Attempts to determine the width of the viewable command line window.
public static function getWidth(int $default = 80): intParameters:
| Parameter | Type | Description |
|---|---|---|
$default | int | Optional default width (default: 80). |
Return:
int - Return terminal window width or default.
getHeight
Attempts to determine the height of the viewable command line window.
public static function getHeight(int $default = 24): intParameters:
| Parameter | Type | Description |
|---|---|---|
$default | int | Optional default height (default: 24). |
Return:
int - Return terminal window height or default.
getStd
Resolve a Terminal stream identifier to its PHP global stream.
Maps Terminal::STD_OUT, Terminal::STD_ERR, and Terminal::STD_INto their corresponding PHP predefined streams (STDOUT, STDERR, STDIN).
Any other value is returned as-is, allowing custom stream handlers.
public static function getStd(mixed $std): mixedParameters:
| Parameter | Type | Description |
|---|---|---|
$std | resource|int | A Terminal stream constant or a custom stream value. |
Return:
resource|mixed - Returns the resolved PHP stream resource, or the original value if it is not a recognized Terminal stream constant.
getSystemInfo
Retrieves key system and environment information in a structured array format.
This method collects details about the PHP runtime, operating system,terminal environment, and framework versions to provide a summarysuitable for diagnostics or display in CLI tools.
public static function getSystemInfo(): arrayReturn:
array<int,array{Name:string,Value:string}> - Return an associative array of system information.
getSystemId
Generates a consistent and unique system identifier for CLI authentication.
This method constructs a persistable identifier by hashing a combination of machine-specific and user-specific data, including the MAC address and key environment/system values.
The result is a unique hash that varies across machines, users, or terminal sessions.
public static function getSystemId(
string $prefix = '',
string $algo = 'sha256',
bool $binary = false
): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$prefix | string | Optional prefix to prepend (default: ''). |
$algo | string | Hashing algorithm to use (default: 'sha256'). |
$binary | bool | Whether to return raw binary output (default: false). |
Return:
string - Return a hashed system identifier based on the specified algorithm.
getPid
Retrieves the parent process ID (PPID) of the current CLI session.
On Unix-like systems, this uses the ps command to obtain the PPID.
On Windows, it uses wmic to extract the parent process ID of the current process. This can help distinguish different terminal sessions or shells launched by the same user.
public static function getPid(): intReturn:
int - Return current PID or 0 if unavailable.
getSystemModel
Retrieve the system's model name (e.g., MacBook Pro, Dell XPS).
public static function getSystemModel(): stringReturn:
string - Return model name or Unknown if not found.
getTerminalName
Retrieves the name of the terminal in use.
For Windows, it tries to detect PowerShell or Command Prompt.On Unix-based systems, it returns the TTY device name.
public static function getTerminalName(): stringReturn:
string - Terminal name or 'N/A' if undetectable.
setColorOutputEnabled
Force enables color output for all standard streams (STDOUT, STDERR, STDIN) without checking whether the terminal or console supports colors.
public static function setColorOutputEnabled(): voidThis method bypasses any checks and ensures that color formatting will be applied to the output, regardless of compatibility.
setAnsiSupportEnabled
Force enables ANSI escape codes (for formatting like text color, cursor movement, etc.) for all standard streams (STDOUT, STDERR, STDIN), without checking whether the terminal or console supports ANSI codes.
public static function setAnsiSupportEnabled(): voidThis method will ensure that ANSI sequences will be processed, regardlessof the actual terminal capabilities.
isColorSupported
Checks if the terminal supports ANSI escape codes for color output.
This method determines whether the current terminal can display colored text,based on the platform and the resource (e.g., STDOUT, STDERR, or STDIN).
public static function isColorSupported(int $std = self::STD_OUT): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$std | int | The std resource to check for color support (e.g, Terminal::STD_OUT, Terminal::STD_ERR or Terminal::STD_IN). |
Return:
bool - Returns true if color output is supported, false otherwise.
Note: On windows you must specify the stream resource (e.g,
Terminal::STD_*).
isAnsiSupported
Checks if the terminal supports ANSI escape codes, including color and text formatting.
This method detects whether the terminal supports ANSI features such as colors, bold, underline,and cursor movement, which are used for enhanced CLI output.
public static function isAnsiSupported(int $std = self::STD_OUT): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$std | int | The std resource to check for ANSI support (e.g, Terminal::STD_OUT, Terminal::STD_ERR or Terminal::STD_IN). |
Return:
bool - Returns true if ANSI escape codes are supported, false otherwise.
isMacTerminal
Checks whether the current terminal is mac terminal.
public static function isMacTerminal(): boolReturn:
bool - Return true if the terminal is a supported macOS terminal, false otherwise.
isWindowsTerminal
Determine whether the current terminal is windows os terminal by passing the stream Terminal::STD_* resource to check on.
public static function isWindowsTerminal(mixed $resource = self::STD_IN): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$resource | resource|string|int | The resource type to check (e.g. Terminal::STD_*, STDIN, STDOUT). |
Return:
bool - Return true if is windows terminal, false otherwise.
isLinuxTerminal
Determines if the current terminal is a supported Linux terminal.
public static function isLinuxTerminal(): boolReturn:
bool - Return true if the terminal is a supported Linux terminal, false otherwise.
isPtySupported
Determines if PTY (Pseudo-Terminal) is supported on the current system.
public static function isPtySupported(): boolReturn:
bool - Return true if PTY is supported, false otherwise.
isTtySupported
Checks if the current system supports TTY (Teletypewriter).
public static function isTtySupported(): boolReturn:
bool - Return true if TTY is supported, false otherwise.
isColorDisabled
Checks whether the no color is available in environment, including command flag --no-color.
public static function isColorDisabled(): boolReturn:
bool - Return true if color is disabled, false otherwise.
isHelp
Check if command is help command.
This method determines if a command is help by search for flag --help or -h in command.
public static function isHelp(string|array|null $command = null): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$command | string|array<array-key, mixed>|null | Command name to check or command array options. |
Return:
bool - Return true if command is help, false otherwise.
isAnsiDisabled
Determines if ANSI escape codes are disabled explicitly, including command flag --no-ansi.
This method checks environment variables and other indicators to determineif ANSI escape codes (for colors, text formatting, etc.) should be disabled.
public static function isAnsiDisabled(): boolReturn:
bool - Returns true if ANSI escape codes are disabled, false otherwise.
hasCommand
Checks whether framework has the requested command.
public static function hasCommand(string $command): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$command | string | Command name to check. |
Return:
bool - Return true if command exist, false otherwise.
hasArgument
Determines if a specific command argument is present.
Supports both short (-f) and long (--flag) forms.
public static function hasArgument(string $name): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$name | string | The command argument to search for (with or without leading dashes). |
Return:
bool - Returns true if the argument exists, false otherwise.
toString
Convert executed command array arguments to their original string form.
public static function toString(array $arguments): ?stringParameters:
| Parameter | Type | Description |
|---|---|---|
$arguments | string[] | The command arguments from $_SERVER['argv']. |
Return:
string|null - Returns the parsed command arguments as a string, or null if the array is empty.
shell
Executes a shell command via shell_exec and return the complete output as a string.
Also it redirects error output to null based on the platform (Windows or Unix-like).
public static function shell(string $command): ?stringParameters:
| Parameter | Type | Description |
|---|---|---|
$command | string | The shell command to execute. |
Return:
string|null - Returns the output of the command if successful, or null on failure.
exception
Renders an exception and its stack trace in the CLI.
public static function exception(Throwable $e): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$e | Throwable | The exception to display. |
Example:
Catch and display an exception from a CLI command.
use Luminova\Command\Terminal;
function loadReport(): void
{
throw new \RuntimeException('Report file is missing.');
}
try {
loadReport();
} catch (\Throwable $e) {
Terminal::exception($e);
}Example output:
Report file is missing.
Class: RuntimeException
File: /path/to/exception-demo.php
Line: 7
Stack trace:
#0 /path/to/exception-demo.php:11 loadReport()
#1 {main}userHome
Get the current user's home directory path.
public static function userHome(): ?stringReturn:
string|null - Return the resolved user home directory, or null if it cannot be determined.
isBinary
Check whether a binary or executable command is available.
public static function isBinary(string $bin, ?string $php = null, bool $posix = false): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$bin | string | Binary name or full path. |
$php | ?string | Optional PHP wrapper for PHAR executables (e.g. 'php' for 'composer.phar'). |
$posix | bool | If true, only checks existence via system lookup (default: false). |
Return:
bool - Return true if the binary is executable and responds successfully, otherwise false.
resolve
Locate the full path of a binary executable.
public static function resolve(
string $bin,
bool $multiple = false,
bool $latest = false,
?string $version = null
): array|string|nullParameters:
| Parameter | Type | Description |
|---|---|---|
$bin | string | The name of the binary to locate (e.g., "php"). |
$multiple | bool | If true, return all matching paths; otherwise, return the first match (default: false). |
$latest | bool | If true the most recently version is returned or at the top (default: false). |
$version | ?string | Optional version number to filter candidates (e.g., 8.2.4). |
Return:
string[]|string|null - Returns a path by default, all matching paths when $multiple is true, or null if no match is found.
where
Find the first matching executable path with resolve().
public static function where(string $bin): ?stringParameters:
| Parameter | Type | Description |
|---|---|---|
$bin | string | The name of the binary to locate. |
Return:
string|null - Returns the first matching path, or null if none is found.
which
Find the first matching executable path with resolve().
public static function which(string $bin): ?stringParameters:
| Parameter | Type | Description |
|---|---|---|
$bin | string | The name of the binary to locate. |
Return:
string|null - Returns the first matching path, or null if none is found.
run
Execute a system command using a safe process wrapper.
public static function run(string $bin, array $args = [], array $options = []): ResultParameters:
| Parameter | Type | Description |
|---|---|---|
$bin | string | The executable binary name or full path to execute. |
$args | array<int|string, mixed> | List of command arguments (unescaped, raw values). |
$options | array{ async?: bool, blocking?: bool, mergeStderr?: bool, timeout?: int, cwd?: string|null, env?: array<array-key, mixed>|null, options?: array<array-key, mixed>|null, throwOnError?: bool } | Execution options controlling process behavior. |
Return:
Result - The execution result containing the exit code, output, and the PID when started asynchronously.
Example:
use Luminova\Command\Terminal;
$result = Terminal::run(PHP_BINARY, ['--version']);
echo $result->output;async
Starts a command as a detached background process.
public static function async(string $command, array $options = []): ?intParameters:
| Parameter | Type | Description |
|---|---|---|
$command | string | Command to execute. |
$options | array{ cwd?: string, pid-pipe?: string, stdout?: string, stderr?: string } | Execution options. |
Return:
int|null - The background process PID, or null on failure.
binExists
Check whether a binary exists in the system PATH.
public static function binExists(string $bin): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$bin | string | The binary name to check (e.g. "php", "git"). |
Return:
bool - True if the binary exists in system PATH.
isSafeBinaryPath
Validate whether a binary reference is safe to execute.
public static function isSafeBinaryPath(string $bin): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$bin | string | Binary name or full executable path. |
Return:
bool - True if the binary reference is considered safe.
isSafeShellArgument
Validate a shell argument for unsafe characters.
public static function isSafeShellArgument(string $value): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$value | string | The argument to validate. |
Return:
bool - True if the argument is safe for shell usage.
isSafeShellPath
Validate a filesystem path string for safe usage.
public static function isSafeShellPath(string $value, bool $allowSpace = false): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$value | string | The filesystem path to validate. |
$allowSpace | bool | Whether spaces are allowed in the path. |
Return:
bool - True if the path is considered safe.
isProcessRunning
Determine whether a PID process is still running.
public static function isProcessRunning(int $pid): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$pid | int | Process ID. |
Return:
bool - Return true if process is running
killProcess
Terminate a running process.
public static function killProcess(int $pid, bool $force = false): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$pid | int | Process ID. |
$force | bool | Forcefully terminate the process. |
Return:
bool - Return true if termination was successful
waitForProcess
Wait for a process to complete.
public static function waitForProcess(
int $pid,
int $timeout = 0,
float $delay = 0.1
): ?intParameters:
| Parameter | Type | Description |
|---|---|---|
$pid | int | The process ID to wait. |
$timeout | int | Timeout in seconds (0 = no timeout). |
$delay | float | Poll delay in seconds (e.g. 0.1 = 100ms). |
Return:
int|null - Returns exit code, or null on timeout/error.
runPhpAsync
Run any PHP file asynchronously in the background.
public static function runPhpAsync(
string $phpFile,
array $arguments = [],
?string $phpPath = null,
?string $cwd = null,
?string $stdout = null,
?int $processTimeout = null
): ?intParameters:
| Parameter | Type | Description |
|---|---|---|
$phpFile | string | Full path to the PHP file to execute. |
$arguments | array<array-key, mixed> | Arguments to pass (key=value, JSON for arrays). |
$phpPath | ?string | Full path to the PHP CLI binary. Auto-detected if null. |
$cwd | ?string | Optional working directory for the PHP process. |
$stdout | ?string | Option stdout redirect file (default: null). |
$processTimeout | ?int | Optional timeout in seconds to wait for process completion. |
Return:
int|null - Returns the background process PID on Unix, null on Windows or failure.
createTempPipePath
Creates a temporary IPC pipe path for command communication.
public static function createTempPipePath(?string $namespace = null): ?stringParameters:
| Parameter | Type | Description |
|---|---|---|
$namespace | ?string | Optional pipe namespace prefix. |
Return:
string|null - Escaped pipe path or null when no pipe is available.
getParentPid
Get the parent process ID (PPID) of the current process.
public static function getParentPid(): intReturn:
int - Parent process ID, or 0 if unavailable.
readPidPipe
Retrieve the PID of a background Windows process from a pipe.
public static function readPidPipe(mixed $source, float $timeout = 2.0): ?intParameters:
| Parameter | Type | Description |
|---|---|---|
$source | resource|string | Pipe resource or pipe name. |
$timeout | float | Maximum time in seconds to wait for the PID. |
Return:
int|null - Return the PID if read successfully, null otherwise.
readInput
Read input from STDIN, supporting single-line or EOF-based input.
public static function readInput(string $default = '', bool $eof = true, bool $newStream = false): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$default | string | Default value returned if input is empty or reading fails. |
$eof | bool | Read until EOF if true, otherwise read a single line. |
$newStream | bool | Open a new STDIN stream as a separate handle. |
Return:
string - Returns trimmed input string or the default value.
escapeArguments
Escapes command arguments for safe shell execution.
public static function escapeArguments(array $arguments): arrayParameters:
| Parameter | Type | Description |
|---|---|---|
$arguments | array<int|string,mixed> | Command arguments. |
Return:
array<int,string> - Escaped shell arguments.