Skip to content

Commit

Permalink
Merge pull request #2523 from 10up/chore/apply-2484
Browse files Browse the repository at this point in the history
Add a "request" subcommand
  • Loading branch information
felipeelia authored Dec 15, 2021
2 parents 07f6dd2 + 603ec5f commit 7f2790c
Showing 1 changed file with 95 additions and 0 deletions.
95 changes: 95 additions & 0 deletions includes/classes/Command.php
Original file line number Diff line number Diff line change
Expand Up @@ -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>
* : Path of the request. Example: `_cat/indices`
*
* [--method=<method>]
* : HTTP Method (GET, POST, etc.)
*
* [--body=<json-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 );
}
}

0 comments on commit 7f2790c

Please sign in to comment.