Luminova Framework

PHP Luminova: Terminal I/O Utilities

Last updated: 2026-11-28 20:57:12

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:

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, 
    0.1, static function (): void { 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_OUTint1Standard output stream, typically used for displaying normal messages or output in a terminal.
STD_ERRint2Standard error stream, used for displaying error messages and diagnostic information.
STD_INint0Standard 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 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 function 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 function waiting(
    int $seconds = 0,
    string $pattern = 'Waiting...(%d seconds)'
): void

Parameters:

ParameterTypeDescription
$secondsintNumber of seconds to wait before continuing (default: 0).
$patternstringMessage 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): void

Parameters:

ParameterTypeDescription
$secondsfloat&#124;intNumber of seconds to pause execution (default: 1).
$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 function spinner(
    array $spinners = ['-', '\\', '|', '/'],
    int $spins = 10,
    float|int $sleep = 0.1,
    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).
$sleepfloat&#124;intDelay in seconds between frames to control animation speed (default: 0.1s).
$onCompleteClosure&#124;bool&#124;nullCallback 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|int

Parameters:

ParameterTypeDescription
$stepint&#124;boolCurrent step of the progress (1-based). Set to false to mark completion.
$stepsintTotal number of steps for the progress (default: 10).
$beepboolWhether 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 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 function watcher(
    int $limit,
    ?Closure $onFinish = null,
    ?Closure $onProgress = null,
    bool $beep = true
): void

Parameters:

ParameterTypeDescription
$limitintTotal number of progress steps.
$onFinishClosure&#124;nullOptional callback executed once when progress reaches 100%.
$onProgressClosure&#124;nullOptional callback executed on each progress step with the current percentage.
$beepboolWhether 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
): string

Parameters:

ParameterTypeDescription
$messagestringThe message to prompt the user with.
$optionsarray<string&#124;int,string&#124;int>Optional list of suggested options.
$validationsstring&#124;bool&#124;nullOptional validation rules: - null (default): automatically uses required|in_array(options) - false: disables validation - string: custom validation rules
$silentboolWhether 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 $required is true, at least one option must be selected.
  • $multiChoice allows selecting multiple options separated by commas.
public static function chooser(
    string $text,
    array $options,
    bool $isRequired = false,
    bool $allowMultiChoice = true
): array

Parameters:

ParameterTypeDescription
$textstringThe message describing the choice.
$optionsarray<string&#124;int,mixed>The list of selectable options. Can be indexed or associative array (keys will still be shown as selection indexes).
$isRequiredboolWhether the user must select at least one option (default: false).
$allowMultiChoiceboolAllow multiple selections separated by commas (default: true).

Return:

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 function 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:

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
): string

Parameters:

ParameterTypeDescription
$prompt?stringOptional message displayed before reading input.
$default?stringDefault value returned if input is empty. Null = required input.
$newStreamboolOpen 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): string

Parameters:

ParameterTypeDescription
$defaultstringDefault value returned if reading fails or input is empty.
$eofboolRead until EOF if true, otherwise a single line.
$newStreamboolOpen 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 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 function tablist(
    array $options,
    int $default = 0,
    ?string $placeholder = null,
    bool $clearOnSelect = true,
    string $foreground = 'green',
    ?string $background = null
): string

Parameters:

ParameterTypeDescription
$optionsarray<int,string&#124;int>The list of selectable options.
$defaultintThe default selected index (0-based).
$placeholder?stringOptional 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').
$background?stringOptional 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
): string

Parameters:

ParameterTypeDescription
$dataarray<int,array<string, string>>Table data, where each row is an associative array of column names and cell values.
$foreground?stringOptional text color for table body (default: null).
$headerColor?stringOptional text color for column headers (default: null).
$borderColor?stringOptional text color for table borders (default: null).
$tableBorderboolWhether to display separators between data rows (default: true).
$shouldRetainNewlinesboolWhether 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
): void

Parameters:

ParameterTypeDescription
$textstringThe error message to display.
$foreground?stringOptional text color (default: white).
$background?stringOptional background color (default: red).
$width?intOptional 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
): void

Parameters:

ParameterTypeDescription
$textstringThe success message to display.
$foreground?stringOptional text color (default: white).
$background?stringOptional background color (default: green).
$width?intOptional 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
): void

Parameters:

ParameterTypeDescription
$textstringThe message to display.
$foreground?stringOptional foreground color (default: blue).
$background?stringOptional background color (default: none).
$width?intOptional 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
): void

Parameters:

ParameterTypeDescription
$textstringThe text to write.
$foreground?stringOptional foreground color name.
$background?stringOptional background color name.
$streamintTarget stream or stream identifier (e.g. Terminal::STD_OUT, STDERR, or custom resource).
$closeHandlerboolWhether 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
): void

Parameters:

ParameterTypeDescription
$textstringThe text to write.
$foreground?stringOptional foreground color name.
$background?stringOptional background color name.
$streamintTarget stream or stream identifier.
$closeHandlerboolWhether to close non-standard streams after writing.

print

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
): void

Parameters:

ParameterTypeDescription
$textstringThe text to print.
$foreground?stringOptional foreground color name.
$background?stringOptional 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): void

Parameters:

ParameterTypeDescription
$textstringThe text to write.
$handlermixedStream identifier, resource, or path.
$closeHandlerboolWhether 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(): 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 function header(): bool

Return:

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(): string

Return:

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:

  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 $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): ?string

Parameters:

ParameterTypeDescription
$version?stringPHP version hint for binary lookup.
$verifyboolIf 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): never

Parameters:

ParameterTypeDescription
$message?stringOptional message to display before exiting.
$exitCodeintExit 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): bool

Parameters:

ParameterTypeDescription
$callbackClosureCallback function to execute on timeout.
$timeoutintTimeout in seconds. If <= 0, the callback is executed immediately (default: 0).
$streamresource&#124;string&#124;intOptional 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|bool

Parameters:

ParameterTypeDescription
$commandstringThe 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): 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 function oops(string $command, ?string $color = 'red'): int

Parameters:

ParameterTypeDescription
$commandstringThe executed command.
$color?stringOptional text color for the command name (default: red).

Return:

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 function link(string $url, ?string $title = null): void

Parameters:

ParameterTypeDescription
$urlstringThe URL to highlight.
$title?stringOptional 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): bool

Parameters:

ParameterTypeDescription
$visibilityboolTrue 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'): 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 function flush(?string $lastOutput = null): void

Parameters:

ParameterTypeDescription
$lastOutput?stringPreviously 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 = []): bool

Parameters:

ParameterTypeDescription
$valuestringThe input value to validate.
$rulesarray<string, string>Validation rules to apply (e.g., required&#124;in_array([yes,no])).
$messagesarray<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): string

Parameters:

ParameterTypeDescription
$argument?stringThe 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): 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:

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:

$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):  void

Parameters:

ParameterTypeDescription
$showCursorboolSet 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): 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 function isStreamSupports(string $function, mixed $resource = self::STD_OUT): bool

Parameters:

ParameterTypeDescription
$functionstringFunction name to check.
$resourceresource&#124;string&#124;intResource 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): int

Parameters:

ParameterTypeDescription
$defaultintOptional 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): int

Parameters:

ParameterTypeDescription
$defaultintOptional 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): mixed

Parameters:

ParameterTypeDescription
$stdresource&#124;intA 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(): array

Return:

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
): string

Parameters:

ParameterTypeDescription
$prefixstringOptional prefix to prepend (default: '').
$algostringHashing algorithm to use (default: 'sha256').
$binaryboolWhether 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(): int

Return:

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(): string

Return:

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(): string

Return:

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(): void

This 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(): void

This 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): bool

Parameters:

ParameterTypeDescription
$stdintThe 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): bool

Parameters:

ParameterTypeDescription
$stdintThe 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(): bool

Return:

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): bool

Parameters:

ParameterTypeDescription
$resourceresource&#124;string&#124;intThe 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(): bool

Return:

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(): bool

Return:

bool - Return true if PTY is supported, false otherwise.


isTtySupported

Checks if the current system supports TTY (Teletypewriter).

public static function isTtySupported(): bool

Return:

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(): bool

Return:

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): bool

Parameters:

ParameterTypeDescription
$commandstring&#124;array<array-key, mixed>&#124;nullCommand 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(): bool

Return:

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): bool

Parameters:

ParameterTypeDescription
$commandstringCommand 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): bool

Parameters:

ParameterTypeDescription
$namestringThe 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): ?string

Parameters:

ParameterTypeDescription
$argumentsstring[]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): ?string

Parameters:

ParameterTypeDescription
$commandstringThe 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): void

Parameters:

ParameterTypeDescription
$eThrowableThe 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(): ?string

Return:

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): bool

Parameters:

ParameterTypeDescription
$binstringBinary name or full path.
$php?stringOptional PHP wrapper for PHAR executables (e.g. 'php' for 'composer.phar').
$posixboolIf 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|null

Parameters:

ParameterTypeDescription
$binstringThe name of the binary to locate (e.g., "php").
$multipleboolIf true, return all matching paths; otherwise, return the first match (default: false).
$latestboolIf true the most recently version is returned or at the top (default: false).
$version?stringOptional 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): ?string

Parameters:

ParameterTypeDescription
$binstringThe 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): ?string

Parameters:

ParameterTypeDescription
$binstringThe 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 = []): Result

Parameters:

ParameterTypeDescription
$binstringThe executable binary name or full path to execute.
$argsarray<int&#124;string, mixed>List of command arguments (unescaped, raw values).
$optionsarray{ async?: bool, blocking?: bool, mergeStderr?: bool, timeout?: int, cwd?: string&#124;null, env?: array<array-key, mixed>&#124;null, options?: array<array-key, mixed>&#124;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 = []): ?int

Parameters:

ParameterTypeDescription
$commandstringCommand to execute.
$optionsarray{ 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): bool

Parameters:

ParameterTypeDescription
$binstringThe 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): bool

Parameters:

ParameterTypeDescription
$binstringBinary 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): bool

Parameters:

ParameterTypeDescription
$valuestringThe 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): bool

Parameters:

ParameterTypeDescription
$valuestringThe filesystem path to validate.
$allowSpaceboolWhether 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): bool

Parameters:

ParameterTypeDescription
$pidintProcess ID.

Return:

bool - Return true if process is running


killProcess

Terminate a running process.

public static function killProcess(int $pid, bool $force = false): bool

Parameters:

ParameterTypeDescription
$pidintProcess ID.
$forceboolForcefully 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
): ?int

Parameters:

ParameterTypeDescription
$pidintThe process ID to wait.
$timeoutintTimeout in seconds (0 = no timeout).
$delayfloatPoll 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
): ?int

Parameters:

ParameterTypeDescription
$phpFilestringFull path to the PHP file to execute.
$argumentsarray<array-key, mixed>Arguments to pass (key=value, JSON for arrays).
$phpPath?stringFull path to the PHP CLI binary. Auto-detected if null.
$cwd?stringOptional working directory for the PHP process.
$stdout?stringOption stdout redirect file (default: null).
$processTimeout?intOptional 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): ?string

Parameters:

ParameterTypeDescription
$namespace?stringOptional 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(): int

Return:

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): ?int

Parameters:

ParameterTypeDescription
$sourceresource&#124;stringPipe resource or pipe name.
$timeoutfloatMaximum 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): string

Parameters:

ParameterTypeDescription
$defaultstringDefault value returned if input is empty or reading fails.
$eofboolRead until EOF if true, otherwise read a single line.
$newStreamboolOpen 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): array

Parameters:

ParameterTypeDescription
$argumentsarray<int&#124;string,mixed>Command arguments.

Return:

array<int,string> - Escaped shell arguments.