PHP Luminova: Command Execution using Process Handler
Run commands or PHP callbacks and collect their output.
Luminova’s Process Handler runs a command, a PHP callable, or a stream operation. The chosen executor controls how command output is collected. Call run() to start the operation, wait() when completion is needed, and getResponse() to read the result.
Features
- Multiple Executors: The class supports running processes using different command execution mechanisms such as:
popenproc_openshell_execexec
- Closure Support: It can execute callable PHP functions or generators, allowing developers to easily run custom code or produce dynamic outputs.
- Stream Interface: It handles stream resources for reading or writing data through file descriptors, making it suitable for dealing with files, network streams, etc.
- Process Lifecycle Management: The class can manage the lifecycle of a process, including starting, running, waiting for completion, and retrieving responses or outputs.
- Timeouts: It includes the ability to wait for a process with a defined timeout to avoid long-running or hanging processes.
Examples
Execute a command with proc_openFor advanced command execution scenarios, it supports running commands using
proc_open, allowing more fine-grained control over input/output streams.use Luminova\Utility\Process; $process = Process::withCommand('echo "Process complete"', Process::EXECUTOR_PROC_OPEN); $process->run(); $process->wait(15); // Wait for up to 15 seconds if ($process->isComplete()) { // Get and output the response $response = $process->getResponse(); echo "Command output:\n"; var_export($response); }Start a process with a callableSupply a PHP callable when the operation is defined in code. The generator example below shows how to collect yielded output.
use Luminova\Utility\Process; $process = Process::withCallback(static function (): Generator { yield "Hello, World!"; }); $process->run(); $process->wait(2);Shell Command Execution with shell_exec:This feature enables executing system commands using
shell_execand capturing their output.use Luminova\Utility\Process; $process = Process::withCommand('ls -la', Process::EXECUTOR_SHELL); $process->run();Handling Stream Resources:The class can read from or write to streams, like files or network resources, using the stream interface.
use Luminova\Utility\Process; $stream = fopen('path/to/file.txt', 'r'); $process = Process::withStream($stream); $process->run(); $process->wait(2); // Get the contents read from the stream if ($process->isComplete()) { $response = $process->getResponse(); echo "Stream content:\n$response"; }Running a Command with popen:The
Processclass allows for running shell commands usingpopen, providing control over the command output and process flow.use Luminova\Utility\Process; $process = Process::withCommand('ls -la', Process::EXECUTOR_POPEN);Waiting for Generator Completion:It can run and wait for PHP generators to complete, making it a versatile tool for handling asynchronous-like operations.
use Luminova\Utility\Process; $generator = function() { yield "Part 1"; yield "Part 2"; }; $process = Process::withCallback($generator); $process->run(); $process->wait(2); // Get the generator's output if ($process->isComplete()) { $response = $process->getResponse(); echo "Generator output:\n" . implode("\n", array_filter((array) $response, 'is_string')); }
Class Definition
- Full namespace:
Luminova\Utility\Process - This class is an ordinary class.
Constants
These constants are predefined process executors which can be pass directory during initialization or along with withCommand method.
| Constant | Visibility | Type | Description |
|---|---|---|---|
EXECUTOR_POPEN | public | string | Executes a command using popen, opening a pipe for process I/O. |
EXECUTOR_EXEC | public | string | Executes a command using exec, running it directly via the shell. |
EXECUTOR_SHELL | public | string | Executes a command using shell_exec, capturing output from the shell. |
EXECUTOR_PROC_OPEN | public | string | Executes a command using proc_open, offering more control over process execution and I/O streams. |
EXECUTOR_CALLBACK | public | string | Executes process using a custom callback function, allowing flexible execution logic. |
EXECUTOR_STREAM | public | string | Executes a process using streams, enabling direct access to input/output streams during execution. |
Process instances cannot be serialized. Store any configuration needed to recreate a process separately.
Methods
__construct
Process constructor.
public function __construct(
mixed $input,
string $executor = self::EXECUTOR_PROC_OPEN,
?string $cwd = null,
?array $env = null
)Parameters:
| Parameter | Type | Description |
|---|---|---|
$input | mixed | Command string, callable, or stream to be executed. |
$executor | string | The process executor type (e.g, Process::EXECUTOR_*) (default: self::EXECUTOR_PROC_OPEN). |
$cwd | string\|null | Optional working directory (default: null). |
$env | array<int\|string,mixed>\|null | Optional environment variables (default: null). |
run
Runs the process based on the provided input and executor.
public function run(): voidReturn:
void - This method does not return a value.
Throws:
- Luminova\Exceptions\RuntimeException - Throws if the process fails to run or any error occurs.
- Luminova\Exceptions\BadMethodCallException - If trying to called while the process is running.
- Luminova\Exceptions\InvalidArgumentException - If an invalid command argument is specified.
withCallback
Creates a Process instance with a callback.
public static function withCallback(callable $callable): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$callable | callable | The callable to be executed. |
Return:
self - Return new static process instance.
withStream
Creates a Process instance with a stream.
public static function withStream(mixed $stream): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$stream | mixed | The stream resource to read from. |
Return:
self - Return new static process instance.
withCommand
Creates a Process instance with a command.
public static function withCommand(
array|string $command,
string $executor = self::EXECUTOR_POPEN,
?string $cwd = null,
?array $envs = null
): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$command | array<int\|string,mixed>\|string | The command to be executed. |
$executor | string | The executor method to use (default: Process::EXECUTOR_POPEN). |
$cwd | string\|null | Optional working directory (default: null). |
$envs | array<string,mixed>\|null | Optional environment variables (default: null). |
Return:
self - Return new static process instance.
isComplete
Checks if the process has completed execution.
public function isComplete(): boolReturn:
bool - Return true if the process has finished; otherwise, false.
isRunning
Check whether the handler has an open execution.
public function isRunning(): boolReturn:
bool - True while the handler is open. Call wait() to collect the response and complete the handler lifecycle.
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.
getResponse
Retrieves the output response from the executed process.The response output, which can be of any type (e.g., string, array).
public function getResponse(): mixedReturn:
mixed - Returns null if the process has not yet run or if no response is available.
getPid
Returns the Pid (process identifier), if applicable.
public function getPid(): ?intReturn:
int|null - The process ID when the handler is open and has a process resource, otherwise null.
getInfo
Read the available process status information.
public function getInfo(): array|boolReturn:
array<string,mixed>|bool - Stored process metadata when the handler is open and has a process resource, or false otherwise. The metadata may be empty. The process status can contain the following fields.
| Key | Type | Description |
|---|---|---|
command | string | Command line used to start the process. |
pid | int | Process identifier. |
running | bool | Whether the process was running when status was read. |
signaled | bool | Whether a signal terminated the process. |
stopped | bool | Whether a signal stopped the process. |
exitcode | int | Reported exit code. |
termsig | int | Terminating signal number. |
stopsig | int | Stopping signal number. |
cached | bool | Whether PHP reported a cached exit code, when available. |
getStartTime
Retrieve the process start time in seconds.
public function getStartTime(): floatReturn:
float - Timestamp in seconds set when wait() begins.
Throws:
- Luminova\Exceptions\RuntimeException - Throws if process is not started
getWorkingDirectory
Gets the working directory.
public function getWorkingDirectory(): ?stringReturn:
string|null - Return the current working directory.
getCommand
Sanitize, replace and retrieve command.
public function getCommand(): stringReturn:
string - Return command string to be executed.
Throws:
- Luminova\Exceptions\InvalidArgumentException - Throws if an error occurs.
setWorkingDirectory
Sets the current working directory.
public function setWorkingDirectory(string $cwd): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$cwd | string | The current working directory. |
Return:
self - Return the instance of process class.
Throws:
- Luminova\Exceptions\BadMethodCallException - If trying to set working directory while the process is running.
setEnvironment
Sets the environment variables.
public function setEnvironment(array $envs): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$envs | array<string,mixed> | The environment variables. |
Return:
self - Return the instance of process class.
Throws:
- Luminova\Exceptions\BadMethodCallException - If trying to set environment variables while the process is running.
setMode
Sets the mode for opens process file pointer.
public function setMode(string $mode): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$mode | string | The mode to use. |
Return:
self - Return the instance of process class.
Throws:
- Luminova\Exceptions\BadMethodCallException - If trying to set mode while the process is running.
setDescriptors
Sets the descriptors specifications.
public function setDescriptors(array $descriptors): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$descriptors | array<int\|string,mixed> | The descriptors specifications. |
Return:
self - Return the instance of process class.
Throws:
- Luminova\Exceptions\BadMethodCallException - If trying to set descriptors while the process is running.
setOptions
Set the process options before execution.
This method allows setting specific options for the process, such as blocking pipes orcreating a new process group. Options cannot be modified once the process is running.
public function setOptions(array $options): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$options | array<string,mixed> | An associative array of options to set. |
Return:
self - Return the instance of process class.
Throws:
- Luminova\Exceptions\RuntimeException - If an invalid option is provided.
- Luminova\Exceptions\BadMethodCallException - If trying to set options while the process is running.
Supported options include:
blocking_pipes: Controls whether the pipes should block during I/O.create_process_group: Determines if the process should be run in a new group.create_new_console: Launches the process in a new console window (Windows only).bypass_shell: Bypass the shell when launching the process (Linux/Windows).detach_process: Detaches the process, allowing it to run independently (Linux/Windows).use_pty: Use a pseudo-terminal (PTY) for the process (Unix systems only).inherit_environment: Inherit the environment variables from the parent process.redirect_stderr: Redirect stderr to stdout (combine output streams).suppress_errors: Suppress PHP errors or warnings during the process execution.
getDescriptors
Gets the descriptors for the process.
public function getDescriptors(): arrayReturn:
array<array-key,mixed> - Custom descriptors when configured, or the default specifications keyed by file descriptor.
| Key | Type | Description |
|---|---|---|
0 | array<int,string> | Standard input opened as a readable pipe by the child. |
1 | array<int,string> | Standard output opened as a writable pipe by the child. |
2 | array<int,string> | Standard error opened as a writable pipe by the child. |
wait
Waits for the process to complete and collects output.
public function wait(int $timeout = 0): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$timeout | int | Maximum time to wait in seconds (default: 0 for no timeout). |
Return:
void - This method does not return a value.
Throws:
- Luminova\Exceptions\RuntimeException - If the process has not been started or if a timeout-aware executor exceeds the configured wait time.