PHP Class WP_CLI, wp-cli

Mostrar archivo Open project: wp-cli/wp-cli Class Usage Examples

Public Methods

Method Description
addCommand ( $name, $class ) back-compat
add_command ( string $name, string $callable, array $args = [] ) : true Register a command to WP-CLI.
add_hook ( string $when, mixed $callback ) : null Schedule a callback to be executed at a certain point.
add_man_dir ( ) DEPRECATED STUFF
add_wp_hook ( string $tag, mixed $function_to_add, integer $priority = 10, integer $accepted_args = 1 ) : true Add a callback to a WordPress action or filter.
colorize ( string $string ) : string Colorize a string for output.
confirm ( string $question, array $assoc_args = [] ) Ask for confirmation before running a destructive operation.
debug ( string $message, string $group = false ) : null Display debug message prefixed with "Debug: " when --debug is used.
do_hook ( string $when ) : null Execute callbacks registered to a given hook.
error ( string | WP_Error $message, boolean | integer $exit = true ) : null Display error message prefixed with "Error: " and exit script.
error_multi_line ( $message_lines ) Display a multi-line error message in a red box. Doesn't exit script.
error_to_string ( mixed $errors ) : string Convert a wp_error into a string
get_cache ( ) : WP_CLI\FileCache
get_config ( string $key = null ) : mixed Get values of global configuration parameters.
get_configurator ( ) : Configurator Get the Configurator instance
get_http_cache_manager ( ) : WP_CLI\WpHttpCacheManager
get_php_binary ( ) : string Get the path to the PHP binary used when executing WP-CLI.
get_root_command ( )
get_runner ( )
get_value_from_arg_or_stdin ( array $args, integer $index ) : string Read value from a positional argument or from STDIN.
halt ( integer $return_code ) Halt script execution with a specific return code.
launch ( string $command, boolean $exit_on_error = true, boolean $return_detailed = false ) : integer | ProcessRun Launch an arbitrary external process that takes over I/O.
launch_self ( string $command, array $args = [], array $assoc_args = [], boolean $exit_on_error = true, boolean $return_detailed = false, array $runtime_args = [] ) : integer | ProcessRun Run a WP-CLI command in a new process reusing the current runtime arguments.
line ( string $message = '' ) : null Display informational message without prefix, and ignore --quiet.
log ( string $message ) Display informational message without prefix.
out ( $str ) back-compat
print_value ( mixed $value, array $assoc_args = [] ) Display a value, in various formats
read_value ( $raw_value, array $assoc_args = [] ) Read a value, from various formats.
run_command ( array $args, array $assoc_args = [] ) Run a given command within the current process using the same global parameters.
runcommand ( string $command, array $options = [] ) : mixed Run a WP-CLI command.
set_logger ( object $logger ) Set the logger instance.
set_url ( $url ) Set the context in which WP-CLI should be run
success ( string $message ) : null Display success message prefixed with "Success: ".
warning ( string $message ) : null Display warning message prefixed with "Warning: ".

Private Methods

Method Description
set_url_params ( $url_parts )
wp_hook_build_unique_id ( $tag, $function, $priority ) Build Unique ID for storage and retrieval.

Method Details

addCommand() public static method

back-compat
public static addCommand ( $name, $class )

add_command() public static method

WP-CLI supports using any callable class, function, or closure as a command. WP_CLI::add_command() is used for both internal and third-party command registration. Command arguments are parsed from PHPDoc by default, but also can be supplied as an optional third argument during registration. # Register a custom 'foo' command to output a supplied positional param. # # $ wp foo bar # Success: bar ** * My awesome closure command * * * : An awesome message to display * * @when before_wp_load *\/ $foo = function( $args ) { WP_CLI::success( $args[0] ); }; WP_CLI::add_command( 'foo', $foo );
public static add_command ( string $name, string $callable, array $args = [] ) : true
$name string Name for the command (e.g. "post list" or "site empty").
$callable string Command implementation as a class, function or closure.
$args array { Optional An associative array with additional registration parameters. 'before_invoke' => callback to execute before invoking the command, 'after_invoke' => callback to execute after invoking the command, 'shortdesc' => short description (80 char or less) for the command, 'synopsis' => the synopsis for the command (string or array), 'when' => execute callback on a named WP-CLI hook (e.g. before_wp_load), }
return true True on success, hard error if registration failed.

add_hook() public static method

Hooks conceptually are very similar to WordPress actions. WP-CLI hooks are typically called before WordPress is loaded. WP-CLI hooks include: * before_invoke: - Just before a command is invoked. * after_invoke: - Just after a command is involved. * before_wp_load - Just before the WP load process begins. * before_wp_config_load - After wp-config.php has been located. * after_wp_config_load - After wp-config.php has been loaded into scope. * after_wp_load - Just after the WP load process has completed. WP-CLI commands can create their own hooks with WP_CLI::do_hook(). # wp network meta confirms command is executing in multisite context. WP_CLI::add_command( 'network meta', 'Network_Meta_Command', array( 'before_invoke' => function () { if ( !is_multisite() ) { WP_CLI::error( 'This is not a multisite install.' ); } } ) );
public static add_hook ( string $when, mixed $callback ) : null
$when string Identifier for the hook.
$callback mixed Callback to execute when hook is called.
return null

add_man_dir() public static method

DEPRECATED STUFF
public static add_man_dir ( )

add_wp_hook() public static method

add_action() without needing access to add_action(). If WordPress is already loaded though, you should use add_action() (and add_filter()) instead.
public static add_wp_hook ( string $tag, mixed $function_to_add, integer $priority = 10, integer $accepted_args = 1 ) : true
$tag string Named WordPress action or filter.
$function_to_add mixed Callable to execute when the action or filter is evaluated.
$priority integer Priority to add the callback as.
$accepted_args integer Number of arguments to pass to callback.
return true

colorize() public static method

Yes, you too can change the color of command line text. For instance, here's how WP_CLI::success() colorizes "Success: " WP_CLI::colorize( "%GSuccess:%n " ) Uses \cli\Colors::colorize() to transform color tokens to display settings. Choose from the following tokens (and note 'reset'): * %y => ['color' => 'yellow'], * %g => ['color' => 'green'], * %b => ['color' => 'blue'], * %r => ['color' => 'red'], * %p => ['color' => 'magenta'], * %m => ['color' => 'magenta'], * %c => ['color' => 'cyan'], * %w => ['color' => 'grey'], * %k => ['color' => 'black'], * %n => ['color' => 'reset'], * %Y => ['color' => 'yellow', 'style' => 'bright'], * %G => ['color' => 'green', 'style' => 'bright'], * %B => ['color' => 'blue', 'style' => 'bright'], * %R => ['color' => 'red', 'style' => 'bright'], * %P => ['color' => 'magenta', 'style' => 'bright'], * %M => ['color' => 'magenta', 'style' => 'bright'], * %C => ['color' => 'cyan', 'style' => 'bright'], * %W => ['color' => 'grey', 'style' => 'bright'], * %K => ['color' => 'black', 'style' => 'bright'], * %N => ['color' => 'reset', 'style' => 'bright'], * %3 => ['background' => 'yellow'], * %2 => ['background' => 'green'], * %4 => ['background' => 'blue'], * %1 => ['background' => 'red'], * %5 => ['background' => 'magenta'], * %6 => ['background' => 'cyan'], * %7 => ['background' => 'grey'], * %0 => ['background' => 'black'], * %F => ['style' => 'blink'], * %U => ['style' => 'underline'], * %8 => ['style' => 'inverse'], * %9 => ['style' => 'bright'], * %_ => ['style' => 'bright')
public static colorize ( string $string ) : string
$string string String to colorize for output, with color tokens.
return string Colorized string.

confirm() public static method

If 'y' is provided to the question, the script execution continues. If 'n' or any other response is provided to the question, script exits. # wp db drop asks for confirmation before dropping the database. WP_CLI::confirm( "Are you sure you want to drop the database?", $assoc_args );
public static confirm ( string $question, array $assoc_args = [] )
$question string Question to display before the prompt.
$assoc_args array Skips prompt if 'yes' is provided.

debug() public static method

Debug message is written to STDERR, and includes script execution time. Helpful for optionally showing greater detail when needed. Used throughout WP-CLI bootstrap process for easier debugging and profiling. # Called in WP_CLI\Runner::set_wp_root(). private static function set_wp_root( $path ) { define( 'ABSPATH', rtrim( $path, '/' ) . '/' ); WP_CLI::debug( 'ABSPATH defined: ' . ABSPATH ); $_SERVER['DOCUMENT_ROOT'] = realpath( $path ); } # Debug details only appear when --debug is used. # $ wp --debug # [...] # Debug: ABSPATH defined: /srv/www/wordpress-develop.dev/src/ (0.225s)
public static debug ( string $message, string $group = false ) : null
$message string Message to write to STDERR.
$group string Organize debug message to a specific group.
return null

do_hook() public static method

See WP_CLI::add_hook() for details on WP-CLI's internal hook system. Commands can provide and call their own hooks.
public static do_hook ( string $when ) : null
$when string Identifier for the hook.
return null

error() public static method

Error message is written to STDERR. Defaults to halting script execution with return code 1. Use WP_CLI::warning() instead when script execution should be permitted to continue. # wp cache flush considers flush failure to be a fatal error. if ( false === wp_cache_flush() ) { WP_CLI::error( 'The object cache could not be flushed.' ); }
public static error ( string | WP_Error $message, boolean | integer $exit = true ) : null
$message string | WP_Error Message to write to STDERR.
$exit boolean | integer True defaults to exit(1).
return null

error_multi_line() public static method

Error message is written to STDERR.
public static error_multi_line ( $message_lines )

error_to_string() public static method

Convert a wp_error into a string
public static error_to_string ( mixed $errors ) : string
$errors mixed
return string

get_cache() public static method

public static get_cache ( ) : WP_CLI\FileCache
return WP_CLI\FileCache

get_config() public static method

Provides access to --path=, --url=, and other values of the global configuration parameters. WP_CLI::log( 'The --url= value is: ' . WP_CLI::get_config( 'url' ) );
public static get_config ( string $key = null ) : mixed
$key string Get value for a specific global configuration parameter.
return mixed

get_configurator() public static method

Get the Configurator instance
public static get_configurator ( ) : Configurator
return WP_CLI\Configurator

get_http_cache_manager() public static method

public static get_http_cache_manager ( ) : WP_CLI\WpHttpCacheManager
return WP_CLI\WpHttpCacheManager

get_php_binary() public static method

Environment values permit specific binaries to be indicated.
public static get_php_binary ( ) : string
return string

get_root_command() public static method

public static get_root_command ( )

get_runner() public static method

public static get_runner ( )

get_value_from_arg_or_stdin() public static method

Read value from a positional argument or from STDIN.
public static get_value_from_arg_or_stdin ( array $args, integer $index ) : string
$args array The list of positional arguments.
$index integer At which position to check for the value.
return string

halt() public static method

Permits script execution to be overloaded by WP_CLI::runcommand()
public static halt ( integer $return_code )
$return_code integer

launch() public static method

# wp core download falls back to the tar binary when PharData isn't available if ( ! class_exists( 'PharData' ) ) { $cmd = "tar xz --strip-components=1 --directory=%s -f $tarball"; WP_CLI::launch( Utils\esc_cmd( $cmd, $dest ) ); return; }
public static launch ( string $command, boolean $exit_on_error = true, boolean $return_detailed = false ) : integer | ProcessRun
$command string External process to launch.
$exit_on_error boolean Whether to exit if the command returns an elevated return code.
$return_detailed boolean Whether to return an exit status (default) or detailed execution results.
return integer | ProcessRun The command exit status, or a ProcessRun object for full details.

launch_self() public static method

Use WP_CLI::runcommand() instead, which is easier to use and works better. Note: While this command does persist a limited set of runtime arguments, it *does not* persist environment variables. Practically speaking, WP-CLI packages won't be loaded when using WP_CLI::launch_self() because the launched process doesn't have access to the current process $HOME.
public static launch_self ( string $command, array $args = [], array $assoc_args = [], boolean $exit_on_error = true, boolean $return_detailed = false, array $runtime_args = [] ) : integer | ProcessRun
$command string WP-CLI command to call.
$args array Positional arguments to include when calling the command.
$assoc_args array Associative arguments to include when calling the command.
$exit_on_error boolean Whether to exit if the command returns an elevated return code.
$return_detailed boolean Whether to return an exit status (default) or detailed execution results.
$runtime_args array Override one or more global args (path,url,user,allow-root)
return integer | ProcessRun The command exit status, or a ProcessRun instance

line() public static method

Message is written to STDOUT. WP_CLI::log() is typically recommended; WP_CLI::line() is included for historical compat.
public static line ( string $message = '' ) : null
$message string Message to display to the end user.
return null

log() public static method

Message is written to STDOUT, or discarded when --quiet flag is supplied. # wp cli update lets user know of each step in the update process. WP_CLI::log( sprintf( 'Downloading from %s...', $download_url ) );
public static log ( string $message )
$message string Message to write to STDOUT.

out() public static method

back-compat
public static out ( $str )

print_value() public static method

Display a value, in various formats
public static print_value ( mixed $value, array $assoc_args = [] )
$value mixed Value to display.
$assoc_args array Arguments passed to the command, determining format.

read_value() public static method

Read a value, from various formats.
public static read_value ( $raw_value, array $assoc_args = [] )
$assoc_args array

run_command() public static method

Use WP_CLI::runcommand() instead, which is easier to use and works better. To run a command using a new process with the same global parameters, use WP_CLI::launch_self(). To run a command using a new process with different global parameters, use WP_CLI::launch(). ob_start(); WP_CLI::run_command( array( 'cli', 'cmd-dump' ) ); $ret = ob_get_clean();
public static run_command ( array $args, array $assoc_args = [] )
$args array Positional arguments including command name.
$assoc_args array

runcommand() public static method

Launch a new child process, or run the command in the current process. Optionally: * Prevent halting script execution on error. * Capture and return STDOUT, or full details about command execution. * Parse JSON output if the command rendered it. $options = array( 'return' => true, // Return 'STDOUT'; use 'all' for full object. 'parse' => 'json', // Parse captured STDOUT to JSON array. 'launch' => false, // Reuse the current process. 'exit_error' => true, // Halt script execution on error. ); $plugins = WP_CLI::runcommand( 'plugin list --format=json', $options );
public static runcommand ( string $command, array $options = [] ) : mixed
$command string WP-CLI command to run, including arguments.
$options array Configuration options for command execution.
return mixed

set_logger() public static method

Set the logger instance.
public static set_logger ( object $logger )
$logger object

set_url() public static method

Set the context in which WP-CLI should be run
public static set_url ( $url )

success() public static method

Success message is written to STDOUT. Typically recommended to inform user of successful script conclusion. # wp rewrite flush expects 'rewrite_rules' option to be set after flush. flush_rewrite_rules( \WP_CLI\Utils\get_flag_value( $assoc_args, 'hard' ) ); if ( ! get_option( 'rewrite_rules' ) ) { WP_CLI::warning( "Rewrite rules are empty." ); } else { WP_CLI::success( 'Rewrite rules flushed.' ); }
public static success ( string $message ) : null
$message string Message to write to STDOUT.
return null

warning() public static method

Warning message is written to STDERR. Use instead of WP_CLI::debug() when script execution should be permitted to continue. # wp plugin activate skips activation when plugin is network active. $status = $this->get_status( $plugin->file ); Network-active is the highest level of activation status if ( 'active-network' === $status ) { WP_CLI::warning( "Plugin '{$plugin->name}' is already network active." ); continue; }
public static warning ( string $message ) : null
$message string Message to write to STDERR.
return null