diff --git a/includes/classes/Command.php b/includes/classes/Command.php index b72a568c5a..4453c43a1f 100644 --- a/includes/classes/Command.php +++ b/includes/classes/Command.php @@ -1807,4 +1807,99 @@ protected function render_stats( $current_index, $body ) { public static function skip_number_format_i18n( $formatted, $number, $decimals ) { return number_format( $number, absint( $decimals ), '.', '' ); } + + /** + * Send a HTTP request to Elasticsearch + * + * ## OPTIONS + * + * + * : Path of the request. Example: `_cat/indices` + * + * [--method=] + * : HTTP Method (GET, POST, etc.) + * + * [--body=] + * : Request body + * + * [--debug-http-request] + * : Enable debugging + * + * @subcommand request + * + * @since 3.6.6 + * + * @param array $args Positional CLI args. + * @param array $assoc_args Associative CLI args. + */ + public function request( $args, $assoc_args ) { + $path = $args[0]; + $method = isset( $assoc_args['method'] ) ? $assoc_args['method'] : 'GET'; + $body = isset( $assoc_args['body'] ) ? $assoc_args['body'] : ''; + $request_args = [ + 'method' => $method, + ]; + if ( 'GET' !== $method && ! empty( $body ) ) { + $request_args['body'] = $body; + } + + if ( ! empty( $assoc_args['debug-http-request'] ) ) { + add_filter( + 'http_api_debug', + function ( $response, $context, $transport, $request_args, $url ) { + WP_CLI::line( + sprintf( + /* translators: URL of the request */ + esc_html__( 'URL: %s', 'elasticpress' ), + $url + ) + ); + WP_CLI::line( + sprintf( + /* translators: Request arguments (outputted with print_r()) */ + esc_html__( 'Request Args: %s', 'elasticpress' ), + print_r( $request_args, true ) + ) + ); + WP_CLI::line( + sprintf( + /* translators: HTTP transport used */ + esc_html__( 'Transport: %s', 'elasticpress' ), + $transport + ) + ); + WP_CLI::line( + sprintf( + /* translators: Context under which the http_api_debug hook is fired */ + esc_html__( 'Context: %s', 'elasticpress' ), + $context + ) + ); + WP_CLI::line( + sprintf( + /* translators: HTTP response (outputted with print_r()) */ + esc_html__( 'Response: %s', 'elasticpress' ), + print_r( $response, true ) + ) + ); + }, + 10, + 5 + ); + } + $response = Elasticsearch::factory()->remote_request( $path, $request_args, [], 'wp_cli_request' ); + + if ( is_wp_error( $response ) ) { + WP_CLI::error( $response->get_error_message() ); + } + + $response_body = wp_remote_retrieve_body( $response ); + $content_type = wp_remote_retrieve_header( $response, 'Content-Type' ); + if ( preg_match( '/json/', $content_type ) ) { + // Re-encode the JSON to add space formatting + $response_body = wp_json_encode( json_decode( $response_body ), JSON_PRETTY_PRINT ); + } + + WP_CLI::log( $response_body ); + } }