Oihana PHP Commands

Kernel extends Command implements LoggerInterface uses CommandTrait, ConfigTrait, ContainerTrait, ConsoleLoggerTrait, DateTrait, FileTrait, HelperTrait, IDTrait, InflectorTrait, JsonOptionsTrait, LifecycleTrait, UITrait

Kernel command class representing a Symfony Console command integrated with dependency injection and extended with multiple traits.

This class provides initialization logic for common command parameters such as actions, batch size, description, and help text.

It implements the PSR-3 LoggerInterface to provide logging capabilities.

Tags
author

Marc Alcaraz (ekameleon)

since
1.0.0

Table of Contents

Interfaces

LoggerInterface

Constants

INFLECTOR  = 'inflector'
The 'inflector' parameter.

Properties

$action  : string|null
The current action of the command, or null if none is selected.
$actions  : array<int, string>
List of possible actions this command can perform.
$batchSize  : int
Number of items to process per batch.
$commandOptions  : CommandOptions|null
The global command options.
$console  : ConsoleLogger|null
The console logger reference.
$inflector  : InflectorInterface
The string inflector reference.
$questionHelper  : QuestionHelper|null
The question helper reference of the command.

Methods

__construct()  : mixed
Kernel constructor.
alert()  : void
Action must be taken immediately.
createProgressBar()  : ProgressBar
Creates and configures a Symfony Console ProgressBar.
createProgressBarFromIO()  : ProgressBar
Creates a progress bar using a SymfonyStyle instance.
critical()  : void
Critical conditions.
debug()  : void
Detailed debug information.
deleteFile()  : int
Deletes a file.
emergency()  : void
System is unusable.
endCommand()  : int
Finalizes the command execution.
error()  : void
Runtime errors that do not require immediate action but should typically be logged and monitored.
exec()  : string
Executes a shell command with optional sudo/user context and silent mode and returns the output of the command.
getQuestionHelper()  : QuestionHelper
Returns the QuestionHelper reference of the command.
info()  : void
Interesting events.
initializeActions()  : static
Initializes the list of actions allowed for this command.
initializeBatchSize()  : static
Initializes the batch size parameter of the command.
initializeConsoleLogger()  : void
Initialize the internal console logger.
initializeDescription()  : static
Initializes the command description.
initializeHelp()  : static
Initializes the help text of the command.
initializeProgressBar()  : static
Applies configuration to a ProgressBar instance.
log()  : void
Logs with an arbitrary level.
makeFile()  : int
Creates a file at the specified path with the given contents.
notice()  : void
Normal but significant events.
proc()  : Process
Executes a shell command using proc_open, capturing stdout, stderr, and the exit status.
progressBarIterator()  : Generator<string|int, T>
Iterate over an iterable collection with a progress bar and optional per-item messages.
system()  : int
Executes a shell command with optional sudo/user context and silent mode.
warning()  : void
Exceptional occurrences that are not errors.
initializeCommandOptions()  : static
Initialize the global command options.
initializeInflector()  : static
Initializes the string inflector to be used by this instance.
initializeKernel()  : static
Initializes the Kernel command with all parameters and dependencies.
startCommand()  : SymfonyStyle, 1: float}
Initializes the command execution.

Constants

INFLECTOR

The 'inflector' parameter.

public mixed INFLECTOR = 'inflector'

Properties

$action

The current action of the command, or null if none is selected.

public string|null $action = null

$actions

List of possible actions this command can perform.

public array<int, string> $actions = []

$batchSize

Number of items to process per batch.

public int $batchSize = 500

$inflector

The string inflector reference.

public InflectorInterface $inflector

$questionHelper

The question helper reference of the command.

public QuestionHelper|null $questionHelper = null

Methods

__construct()

Kernel constructor.

public __construct(string|null $name, Container $container[, array<string|int, mixed> $init = [] ]) : mixed

Initializes the command with the given name and injects the DI container and parameters.

Parameters
$name : string|null

The command name, or null to be set in configure().

$container : Container

The dependency injection container.

$init : array<string|int, mixed> = []

Initialization parameters for the command.

Tags
throws
DependencyException
throws
NotFoundException
throws
ContainerExceptionInterface
throws
NotFoundExceptionInterface

alert()

Action must be taken immediately.

public alert(string|Stringable $message[, array<string|int, mixed> $context = [] ]) : void

Example: Entire website down, database unavailable, etc. This should trigger the SMS alerts and wake you up.

Parameters
$message : string|Stringable
$context : array<string|int, mixed> = []

createProgressBar()

Creates and configures a Symfony Console ProgressBar.

public createProgressBar(OutputInterface $output[, int $max = 0 ][, string $format = 'pretty' ][, int $barWidth = 50 ][, array<string|int, mixed>|null $formatDefinitions = null ]) : ProgressBar
Parameters
$output : OutputInterface

The output interface (usually from a command).

$max : int = 0

The maximum number of steps (0 for indeterminate).

$format : string = 'pretty'

The format name to use (e.g., 'pretty').

$barWidth : int = 50

The width of the progress bar.

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

Custom format definitions [name => format string].

Return values
ProgressBar

The initialized progress bar instance.

createProgressBarFromIO()

Creates a progress bar using a SymfonyStyle instance.

public createProgressBarFromIO(SymfonyStyle $io[, int $max = 0 ][, string $format = 'pretty' ][, int $barWidth = 50 ][, array<string|int, mixed>|null $formatDefinitions = null ]) : ProgressBar
Parameters
$io : SymfonyStyle

The SymfonyStyle instance.

$max : int = 0

The maximum number of steps.

$format : string = 'pretty'

The format name to use.

$barWidth : int = 50

The width of the progress bar.

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

Custom format definitions [name => format string].

Return values
ProgressBar

The initialized progress bar instance.

critical()

Critical conditions.

public critical(string|Stringable $message[, array<string|int, mixed> $context = [] ]) : void

Example: Application component unavailable, unexpected exception.

Parameters
$message : string|Stringable
$context : array<string|int, mixed> = []

debug()

Detailed debug information.

public debug(string|Stringable $message[, array<string|int, mixed> $context = [] ]) : void
Parameters
$message : string|Stringable
$context : array<string|int, mixed> = []

deleteFile()

Deletes a file.

public deleteFile(string|null $filePath[, null|array<string|int, mixed>|CommandOptions $options = null ][, bool $verbose = false ][, bool $assertable = false ][, bool $sudo = false ][, bool $dryRun = false ]) : int
Parameters
$filePath : string|null

The absolute path to the file to create.

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

Optional command options, such as sudo or user context.

$verbose : bool = false

Whether to output verbose logs.

$assertable : bool = false

If true, asserts file existence and permissions before deletion.

$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
FileException

It the file path is not valid or the file not exist.

Return values
int

emergency()

System is unusable.

public emergency(string|Stringable $message[, array<string|int, mixed> $context = [] ]) : void
Parameters
$message : string|Stringable
$context : array<string|int, mixed> = []

endCommand()

Finalizes the command execution.

public endCommand(InputInterface $input, OutputInterface $output[, int $status = ExitCode::SUCCESS ][, float $timestamp = 0 ]) : int

Displays a completion section in the console output with an optional execution time, followed by a short farewell message. Returns the provided status code.

Parameters
$input : InputInterface

The console input instance.

$output : OutputInterface

The console output instance.

$status : int = ExitCode::SUCCESS

The return status code (default: ExitCode::SUCCESS).

$timestamp : float = 0

The starting UNIX timestamp for execution time calculation (default: 0).

Tags
example
return $this->endCommand($input, $output, ExitCode::SUCCESS, $startTime);
Return values
int

The status code to return from the command.

error()

Runtime errors that do not require immediate action but should typically be logged and monitored.

public error(string|Stringable $message[, array<string|int, mixed> $context = [] ]) : void
Parameters
$message : string|Stringable
$context : array<string|int, mixed> = []

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.

getQuestionHelper()

Returns the QuestionHelper reference of the command.

public getQuestionHelper() : QuestionHelper
Return values
QuestionHelper

info()

Interesting events.

public info(string|Stringable $message[, array<string|int, mixed> $context = [] ]) : void

Example: User logs in, SQL logs.

Parameters
$message : string|Stringable
$context : array<string|int, mixed> = []

initializeActions()

Initializes the list of actions allowed for this command.

public initializeActions([array<string|int, mixed> $init = [] ]) : static
Parameters
$init : array<string|int, mixed> = []

Initialization parameters which may contain 'actions' key.

Return values
static

Returns the instance for method chaining.

initializeBatchSize()

Initializes the batch size parameter of the command.

public initializeBatchSize([array<string|int, mixed> $init = [] ]) : static
Parameters
$init : array<string|int, mixed> = []

Initialization parameters which may contain 'batchSize' key.

Return values
static

Returns the instance for method chaining.

initializeConsoleLogger()

Initialize the internal console logger.

public initializeConsoleLogger([OutputInterface|null $output = null ][, array<string|int, mixed> $verbosityLevelMap = [] ][, array<string|int, mixed> $formatLevelMap = [] ]) : void
Parameters
$output : OutputInterface|null = null
$verbosityLevelMap : array<string|int, mixed> = []
$formatLevelMap : array<string|int, mixed> = []

initializeDescription()

Initializes the command description.

public initializeDescription([array<string|int, mixed> $init = [] ]) : static

If a non-empty description is provided in the initialization parameters, it will be set for the command.

Parameters
$init : array<string|int, mixed> = []

Initialization parameters which may contain 'description' key.

Return values
static

Returns the instance for method chaining.

initializeHelp()

Initializes the help text of the command.

public initializeHelp([array<string|int, mixed> $init = [] ]) : static

If a non-empty help string is provided in the initialization parameters, it will be set for the command.

Parameters
$init : array<string|int, mixed> = []

Initialization parameters which may contain 'help' key.

Return values
static

Returns the instance for method chaining.

initializeProgressBar()

Applies configuration to a ProgressBar instance.

public initializeProgressBar(ProgressBar $progressBar[, string $format = 'pretty' ][, int $barWidth = 50 ][, array<string|int, mixed>|null $formatDefinitions = null ]) : static
Parameters
$progressBar : ProgressBar

The progress bar to initialize.

$format : string = 'pretty'

The format name to use (e.g., 'pretty').

$barWidth : int = 50

The width of the progress bar.

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

Optional array of custom format definitions.

Return values
static

The current trait instance (for method chaining).

log()

Logs with an arbitrary level.

public log(mixed $level, string|Stringable $message[, array<string|int, mixed> $context = [] ]) : void
Parameters
$level : mixed
$message : string|Stringable
$context : array<string|int, mixed> = []

makeFile()

Creates a file at the specified path with the given contents.

public makeFile(string|null $filePath[, string|null $content = '' ][, null|array<string|int, mixed>|CommandOptions $options = null ][, bool $verbose = false ][, bool $sudo = false ][, bool $dryRun = false ]) : int

If the parent directory does not exist, it is created.

Parameters
$filePath : string|null

The absolute path to the file to create.

$content : string|null = ''

The content to write; if null, an empty file is created@param null|array|CommandOptions $options Optional command options, such as sudo or user context..

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

Optional command options, such as sudo or user context.

$verbose : bool = false

Whether to output verbose logs.

$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 directory or file cannot be created.

example
$this->createFile
(
    '/var/www/html/robots.txt',
    'User-agent: *' . PHP_EOL . 'Disallow: /private/'
);
Return values
int

ExitCode::SUCCESS (0) if the file creation succeeds.

notice()

Normal but significant events.

public notice(string|Stringable $message[, array<string|int, mixed> $context = [] ]) : void
Parameters
$message : string|Stringable
$context : array<string|int, mixed> = []

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

progressBarIterator()

Iterate over an iterable collection with a progress bar and optional per-item messages.

public progressBarIterator(ProgressBar|null $progressBar, iterable<string|int, T$items[, callable(T): string|string|null $message = null ][, string|null $start = null ][, string|null $finish = null ]) : Generator<string|int, T>

Example usage:

$iterator = $this->progressBarIterator( $progressBar , $items , fn($item) => "Processing {$item->name}") ;
foreach ( $iterator as $item)
{
    // Process $item here
}
Parameters
$progressBar : ProgressBar|null

The progress bar reference.

$items : iterable<string|int, T>

Iterable collection of items.

$message : callable(T): string|string|null = null

Optional callback to generate message per item: fn(T): string.

$start : string|null = null

The message when the iteration is starting.

$finish : string|null = null

The message when the iteration is ending.

Return values
Generator<string|int, T>

Generator yielding each item.

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).

warning()

Exceptional occurrences that are not errors.

public warning(string|Stringable $message[, array<string|int, mixed> $context = [] ]) : void

Example: Use of deprecated APIs, poor use of an API, undesirable things that are not necessarily wrong.

Parameters
$message : string|Stringable
$context : array<string|int, mixed> = []

initializeCommandOptions()

Initialize the global command options.

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

initializeInflector()

Initializes the string inflector to be used by this instance.

protected initializeInflector([array<string, mixed> $init = [] ][, ContainerInterface|null $container = null ][, InflectorInterface|null $defaultInflector = null ]) : static

This method determines which InflectorInterface implementation should be applied:

  • If $init[static::INFLECTOR] is a non-empty string corresponding to a service name available in the DI container, that service will be fetched and used as the inflector.
  • If $init[static::INFLECTOR] is already an InflectorInterface instance, it is used directly.
  • Otherwise, the provided $defaultInflector is used; if not given, a new EnglishInflector is created.
Parameters
$init : array<string, mixed> = []

Optional initialization parameters. May contain the key static::INFLECTOR with:

  • A service ID (string) resolvable via $container
  • Or an InflectorInterface instance.
$container : ContainerInterface|null = null

Optional PSR-11 container for resolving a service name into an InflectorInterface.

$defaultInflector : InflectorInterface|null = null

Fallback inflector to use if no specific instance is found or provided.

Tags
throws
ContainerExceptionInterface

If the container encounters an error while retrieving the inflector service.

throws
NotFoundExceptionInterface

If the requested inflector service is not found in the container.

Return values
static

Returns the current instance for method chaining.

initializeKernel()

Initializes the Kernel command with all parameters and dependencies.

protected initializeKernel(Container $container[, array<string|int, mixed> $init = [] ]) : static

This method configures the container, command options, configuration, description, help, IDs, inflectors, and JSON options.

Parameters
$container : Container

Dependency Injection container instance.

$init : array<string|int, mixed> = []

Initialization parameters for the command.

Tags
throws
ContainerExceptionInterface
throws
DependencyException
throws
NotFoundException
throws
NotFoundExceptionInterface
Return values
static

Returns the instance for method chaining.

startCommand()

Initializes the command execution.

protected startCommand(InputInterface $input, OutputInterface $output) : SymfonyStyle, 1: float}

Displays a formatted title in the console containing the command name and an optional action property, then returns the I/O helper instance and the current UNIX timestamp.

Parameters
$input : InputInterface

The console input instance.

$output : OutputInterface

The console output instance.

Tags
example
[$io, $startTime] = $this->startCommand($input, $output);
Return values
SymfonyStyle, 1: float}

An array containing the SymfonyStyle I/O instance and the current timestamp.


        
On this page

Search results