public static function add_command($name, $callable, $args = array())
{
$valid = false;
if (is_callable($callable)) {
$valid = true;
} else {
if (is_string($callable) && class_exists((string) $callable)) {
$valid = true;
} else {
if (is_object($callable)) {
$valid = true;
}
}
}
if (!$valid) {
if (is_array($callable)) {
$callable[0] = is_object($callable[0]) ? get_class($callable[0]) : $callable[0];
$callable = array($callable[0], $callable[1]);
}
WP_CLI::error(sprintf("Callable %s does not exist, and cannot be registered as `wp %s`.", json_encode($callable), $name));
}
foreach (array('before_invoke', 'after_invoke') as $when) {
if (isset($args[$when])) {
self::add_hook("{$when}:{$name}", $args[$when]);
}
}
$path = preg_split('/\\s+/', $name);
$leaf_name = array_pop($path);
$full_path = $path;
$command = self::get_root_command();
while (!empty($path)) {
$subcommand_name = $path[0];
$subcommand = $command->find_subcommand($path);
// create an empty container
if (!$subcommand) {
$subcommand = new Dispatcher\CompositeCommand($command, $subcommand_name, new \WP_CLI\DocParser(''));
$command->add_subcommand($subcommand_name, $subcommand);
}
$command = $subcommand;
}
$leaf_command = Dispatcher\CommandFactory::create($leaf_name, $callable, $command);
if (!$command->can_have_subcommands()) {
throw new Exception(sprintf("'%s' can't have subcommands.", implode(' ', Dispatcher\get_path($command))));
}
if (isset($args['shortdesc'])) {
$leaf_command->set_shortdesc($args['shortdesc']);
}
if (isset($args['synopsis'])) {
if (is_string($args['synopsis'])) {
$leaf_command->set_synopsis($args['synopsis']);
} else {
if (is_array($args['synopsis'])) {
$synopsis = \WP_CLI\SynopsisParser::render($args['synopsis']);
$leaf_command->set_synopsis($synopsis);
$long_desc = '';
$bits = explode(' ', $synopsis);
foreach ($args['synopsis'] as $key => $arg) {
$long_desc .= $bits[$key] . PHP_EOL;
if (!empty($arg['description'])) {
$long_desc .= ': ' . $arg['description'] . PHP_EOL;
}
$yamlify = array();
foreach (array('default', 'options') as $key) {
if (isset($arg[$key])) {
$yamlify[$key] = $arg[$key];
}
}
if (!empty($yamlify)) {
$long_desc .= \Spyc::YAMLDump($yamlify);
$long_desc .= '---' . PHP_EOL;
}
$long_desc .= PHP_EOL;
}
if (!empty($long_desc)) {
$long_desc = rtrim($long_desc, PHP_EOL);
$long_desc = '## OPTIONS' . PHP_EOL . PHP_EOL . $long_desc;
$leaf_command->set_longdesc($long_desc);
}
}
}
}
if (isset($args['when'])) {
self::get_runner()->register_early_invoke($args['when'], $leaf_command);
}
$command->add_subcommand($leaf_name, $leaf_command);
return true;
}