WP_CLI::runcommand PHP Method

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
    public static function runcommand($command, $options = array())
    {
        $defaults = array('launch' => true, 'exit_error' => true, 'return' => false, 'parse' => false);
        $options = array_merge($defaults, $options);
        $launch = $options['launch'];
        $exit_error = $options['exit_error'];
        $return = $options['return'];
        $parse = $options['parse'];
        $retval = null;
        if ($launch) {
            if ($return) {
                $descriptors = array(0 => STDIN, 1 => array('pipe', 'w'), 2 => array('pipe', 'w'));
            } else {
                $descriptors = array(0 => STDIN, 1 => STDOUT, 2 => STDERR);
            }
            $php_bin = self::get_php_binary();
            $script_path = $GLOBALS['argv'][0];
            // Persist runtime arguments unless they've been specified otherwise.
            $configurator = \WP_CLI::get_configurator();
            $argv = array_slice($GLOBALS['argv'], 1);
            list($_, $_, $runtime_config) = $configurator->parse_args($argv);
            foreach ($runtime_config as $k => $v) {
                if (preg_match("|^--{$key}=?\$|", $command)) {
                    unset($runtime_config[$k]);
                }
            }
            $runtime_config = Utils\assoc_args_to_str($runtime_config);
            $runcommand = "{$php_bin} {$script_path} {$runtime_config} {$command}";
            $env_vars = array('HOME', 'WP_CLI_AUTO_CHECK_UPDATE_DAYS', 'WP_CLI_CACHE_DIR', 'WP_CLI_CONFIG_PATH', 'WP_CLI_DISABLE_AUTO_CHECK_UPDATE', 'WP_CLI_PACKAGES_DIR', 'WP_CLI_PHP_USED', 'WP_CLI_PHP', 'WP_CLI_STRICT_ARGS_MODE');
            $env = array();
            foreach ($env_vars as $var) {
                $env[$var] = getenv($var);
            }
            $proc = proc_open($runcommand, $descriptors, $pipes, getcwd(), $env);
            if ($return) {
                $stdout = stream_get_contents($pipes[1]);
                fclose($pipes[1]);
                $stderr = stream_get_contents($pipes[2]);
                fclose($pipes[2]);
            }
            $return_code = proc_close($proc);
            if (-1 == $return_code) {
                self::warning("Spawned process returned exit code -1, which could be caused by a custom compiled version of PHP that uses the --enable-sigchild option.");
            } else {
                if ($return_code && $exit_error) {
                    exit($return_code);
                }
            }
            if (true === $return || 'stdout' === $return) {
                $retval = trim($stdout);
            } else {
                if ('stderr' === $return) {
                    $retval = trim($stderr);
                } else {
                    if ('return_code' === $return) {
                        $retval = $return_code;
                    } else {
                        if ('all' === $return) {
                            $retval = (object) array('stdout' => trim($stdout), 'stderr' => trim($stderr), 'return_code' => $return_code);
                        }
                    }
                }
            }
        } else {
            $configurator = self::get_configurator();
            $argv = Utils\parse_str_to_argv($command);
            list($args, $assoc_args, $runtime_config) = $configurator->parse_args($argv);
            if ($return) {
                ob_start();
                $existing_logger = self::$logger;
                self::$logger = new WP_CLI\Loggers\Execution();
            }
            if (!$exit_error) {
                self::$capture_exit = true;
            }
            try {
                self::get_runner()->run_command($args, $assoc_args, array('back_compat_conversions' => true));
                $return_code = 0;
            } catch (ExitException $e) {
                $return_code = $e->getCode();
            }
            if ($return) {
                $execution_logger = self::$logger;
                self::$logger = $existing_logger;
                $stdout = trim(ob_get_clean());
                $stderr = $execution_logger->stderr;
                if (true === $return || 'stdout' === $return) {
                    $retval = trim($stdout);
                } else {
                    if ('stderr' === $return) {
                        $retval = trim($stderr);
                    } else {
                        if ('return_code' === $return) {
                            $retval = $return_code;
                        } else {
                            if ('all' === $return) {
                                $retval = (object) array('stdout' => trim($stdout), 'stderr' => trim($stderr), 'return_code' => $return_code);
                            }
                        }
                    }
                }
            }
            if (!$exit_error) {
                self::$capture_exit = false;
            }
        }
        if ((true === $return || 'stdout' === $return) && 'json' === $parse) {
            $retval = json_decode($retval, true);
        }
        return $retval;
    }

Usage Example

Example #1
0
 /**
  * Update the permalink structure.
  *
  * Sets the post permalink structure to the specified pattern.
  *
  * To regenerate a .htaccess file with WP-CLI, you'll need to add
  * the mod_rewrite module to your [WP-CLI config](http://wp-cli.org/config/).
  * For example:
  *
  * ```
  * apache_modules:
  *   - mod_rewrite
  * ```
  *
  * ## OPTIONS
  *
  * <permastruct>
  * : The new permalink structure to apply.
  *
  * [--category-base=<base>]
  * : Set the base for category permalinks, i.e. '/category/'.
  *
  * [--tag-base=<base>]
  * : Set the base for tag permalinks, i.e. '/tag/'.
  *
  * [--hard]
  * : Perform a hard flush - update `.htaccess` rules as well as rewrite rules in database.
  *
  * ## EXAMPLES
  *
  *     $ wp rewrite structure '/%year%/%monthnum%/%postname%'
  *     Success: Rewrite structure set.
  */
 public function structure($args, $assoc_args)
 {
     global $wp_rewrite;
     // copypasta from /wp-admin/options-permalink.php
     $prefix = $blog_prefix = '';
     if (is_multisite() && !is_subdomain_install() && is_main_site()) {
         $blog_prefix = '/blog';
     }
     $permalink_structure = $args[0] == 'default' ? '' : $args[0];
     if (!empty($permalink_structure)) {
         $permalink_structure = preg_replace('#/+#', '/', '/' . str_replace('#', '', $permalink_structure));
         if ($prefix && $blog_prefix) {
             $permalink_structure = $prefix . preg_replace('#^/?index\\.php#', '', $permalink_structure);
         } else {
             $permalink_structure = $blog_prefix . $permalink_structure;
         }
     }
     $wp_rewrite->set_permalink_structure($permalink_structure);
     // Update category or tag bases
     if (isset($assoc_args['category-base'])) {
         $category_base = $assoc_args['category-base'];
         if (!empty($category_base)) {
             $category_base = $blog_prefix . preg_replace('#/+#', '/', '/' . str_replace('#', '', $category_base));
         }
         $wp_rewrite->set_category_base($category_base);
     }
     if (isset($assoc_args['tag-base'])) {
         $tag_base = $assoc_args['tag-base'];
         if (!empty($tag_base)) {
             $tag_base = $blog_prefix . preg_replace('#/+#', '/', '/' . str_replace('#', '', $tag_base));
         }
         $wp_rewrite->set_tag_base($tag_base);
     }
     // make sure we detect mod_rewrite if configured in apache_modules in config
     self::apache_modules();
     // Launch a new process to flush rewrites because core expects flush
     // to happen after rewrites are set
     $new_assoc_args = array();
     $cmd = 'rewrite flush';
     if (\WP_CLI\Utils\get_flag_value($assoc_args, 'hard')) {
         $cmd .= ' --hard';
         $new_assoc_args['hard'] = true;
         if (!in_array('mod_rewrite', (array) WP_CLI::get_config('apache_modules'))) {
             WP_CLI::warning("Regenerating a .htaccess file requires special configuration. See usage docs.");
         }
     }
     $process_run = WP_CLI::runcommand($cmd);
     if (!empty($process_run->stderr)) {
         // Strip "Warning: "
         WP_CLI::warning(substr($process_run->stderr, 9));
     }
     WP_CLI::success("Rewrite structure set.");
 }
All Usage Examples Of WP_CLI::runcommand