Oihana PHP Commands

SudoTrait uses trait:short

Trait to handle sudo authentication and session management for commands.

Provides methods to:

  • Authenticate with sudo once to cache credentials.
  • Optionally keep the sudo session alive by refreshing credentials in the background.
  • Stop the background keep-alive process.

This trait is useful for commands that require elevated privileges and want to avoid repeatedly prompting for the sudo password.

Usage Example

use oihana\commands\traits\SudoTrait;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class MySudoCommand extends Command
{
    use SudoTrait;

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        try {
            $this->sudoAuthenticate(null, true, false, true);
            // Run privileged operations here...
        } catch (\RuntimeException $e) {
            $output->writeln('<error>' . $e->getMessage() . '</error>');
            return 1;
        }

        // Optionally stop the keep-alive process later
        $this->sudoStopKeepAlive(true);

        return 0;
    }
}
Tags
author

Marc Alcaraz

since
1.0.0

Table of Contents

Properties

$commandOptions  : CommandOptions|null
The global command options.

Methods

exec()  : string
Executes a shell command with optional sudo/user context and silent mode and returns the output of the command.
proc()  : Process
Executes a shell command using proc_open, capturing stdout, stderr, and the exit status.
sudoAuthenticate()  : int
Attempts to authenticate with sudo once to cache credentials for subsequent commands.
sudoStopKeepAlive()  : bool
Stops the background sudo keep-alive process if it is running.
system()  : int
Executes a shell command with optional sudo/user context and silent mode.
initializeCommandOptions()  : static
Initialize the global command options.

Properties

Methods

exec()

Executes a shell command with optional sudo/user context and silent mode and returns the output of the command.

public exec(null|array<string|int, mixed>|string $command[, null|array<string|int, mixed>|string $args = null ][, CommandOptions|null $options = null ][, bool $silent = false ][, bool $verbose = false ][, string|null $previous = null ][, string|null $post = null ][, bool $sudo = false ][, bool $dryRun = false ]) : string
Parameters
$command : null|array<string|int, mixed>|string

The base shell command to execute (e.g. "wp plugin install").

$args : null|array<string|int, mixed>|string = null

Optional additional arguments appended to the command, a string or an array of arguments.

$options : CommandOptions|null = null

Whether to prefix the command with sudo. Defaults to $this->sudo.

$silent : bool = false

Whether to suppress the command's output.

$verbose : bool = false

Verbose the error message.

$previous : string|null = null

The previous command to append.

$post : string|null = null

The post command to append at the end.

$sudo : bool = false

If true, the command is automatically prefixed with sudo to run with elevated privileges.

$dryRun : bool = false

If true, simulates the execution without actually running the command. Always returns 0.

Tags
throws
RuntimeException

If the command returned no output.

example
$this->system('wp theme install hello-elementor', '--path=/var/www/site' );
$this->system('ls', '-la', new CommandOptions([ 'sudo' => true, 'user' => 'www-data');
Return values
string

The output of the command.

proc()

Executes a shell command using proc_open, capturing stdout, stderr, and the exit status.

public proc(null|array<string|int, mixed>|string $command[, null|array<string|int, mixed>|string $args = null ][, CommandOptions|null $options = null ][, bool $verbose = false ][, string|null $previous = null ][, string|null $post = null ][, bool $sudo = false ][, bool $dryRun = false ]) : Process

This method builds a full command from the base command, optional arguments, and optional sudo/user context. It provides full control over the execution environment and captures both standard output and error output separately.

Parameters
$command : null|array<string|int, mixed>|string

The base shell command to execute (e.g. "wp plugin list").

$args : null|array<string|int, mixed>|string = null

Optional arguments to pass to the command. Can be a string or array.

$options : CommandOptions|null = null

Optional command options, such as sudo or user context.

$verbose : bool = false

Whether to display the full command before execution.

$previous : string|null = null

The previous command to append.

$post : string|null = null

The post command to append at the end.

$sudo : bool = false

If true, the command is automatically prefixed with sudo to run with elevated privileges.

$dryRun : bool = false

If true, simulates the execution without actually running the command. Always returns 0.

Tags
throws
RuntimeException

If the process could not be started.

example
$result = $this->proc( 'wp post list' , ' --format=ids') ;
if ( $result->status === 0 )
{
    $ids = explode( PHP_EOL , $result->output ) ;
}
Return values
Process

sudoAuthenticate()

Attempts to authenticate with sudo once to cache credentials for subsequent commands.

public sudoAuthenticate([CommandOptions|null $options = null ][, bool $keepAlive = false ][, bool $silent = false ][, bool $verbose = false ]) : int

Optionally keeps the sudo session alive by refreshing the authentication token in the background at regular intervals (non-blocking).

Parameters
$options : CommandOptions|null = null
$keepAlive : bool = false

Whether to keep the sudo session active by refreshing it every 60 seconds.

$silent : bool = false

Whether to suppress the output of the sudo commands.

$verbose : bool = false

Whether to display verbose output and error messages.

Tags
throws
RuntimeException

If the initial sudo authentication fails or is cancelled by the user.

Return values
int

Returns the exit code of the sudo command (0 if successful).

sudoStopKeepAlive()

Stops the background sudo keep-alive process if it is running.

public sudoStopKeepAlive([bool $verbose = false ]) : bool
Parameters
$verbose : bool = false

Whether to output status messages.

Return values
bool

True if the process was found and killed, false otherwise.

system()

Executes a shell command with optional sudo/user context and silent mode.

public system(null|array<string|int, mixed>|string $command[, null|array<string|int, mixed>|string $args = null ][, null|array<string|int, mixed>|CommandOptions $options = null ][, bool $silent = false ][, bool $verbose = false ][, string|null $previous = null ][, string|null $post = null ][, bool $sudo = false ][, bool $dryRun = false ]) : int

This method builds and executes a shell command string, optionally prefixed with sudo -u <user>. It can suppress output using the makeSilent() method and throws an exception on failure.

Parameters
$command : null|array<string|int, mixed>|string

The base shell command to execute (e.g. "wp plugin install").

$args : null|array<string|int, mixed>|string = null

Optional additional arguments appended to the command, a string or an array of arguments.

$options : null|array<string|int, mixed>|CommandOptions = null

Whether to prefix the command with sudo. Defaults to $this->sudo.

$silent : bool = false

Whether to suppress the command's output.

$verbose : bool = false

Verbose the error message.

$previous : string|null = null

Optional command to prepend (e.g., cd /path &&).

$post : string|null = null

Optional command to append after execution (e.g., ; echo done).

$sudo : bool = false

If true, the command is automatically prefixed with sudo to run with elevated privileges.

$dryRun : bool = false

If true, simulates the execution without actually running the command. Always returns 0.

Tags
throws
RuntimeException

RuntimeException If the command fails and $dryRun is false.

example
$this->system('wp theme install hello-elementor', '--path=/var/www/site' );
$this->system('ls', '-la', new CommandOptions([ 'sudo' => true, 'user' => 'www-data');
$this->system('rm -rf /tmp/sandbox', verbose:true, dryRun: true); // dry-run, shows command
Return values
int

The result code of the command (0 if successful).

initializeCommandOptions()

Initialize the global command options.

protected initializeCommandOptions([array<string|int, mixed> $init = [] ]) : static
Parameters
$init : array<string|int, mixed> = []
Return values
static

        
On this page

Search results