Skip to content

Commit

Permalink
set response pieces correctly
Browse files Browse the repository at this point in the history
  • Loading branch information
mogmarsh committed May 2, 2024
1 parent 5ecc6e9 commit e570410
Showing 1 changed file with 38 additions and 1 deletion.
39 changes: 38 additions & 1 deletion src/class-service.php
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,44 @@ protected function get_response( WP_REST_Request $request, string $url, array $a
*/
$response = apply_filters( 'wp_proxy_service_response_after_request', $response, $request, $url );

return rest_ensure_response( $response );
// Check for a successful response.
if ( is_wp_error( $response ) ) {
return new WP_REST_Response(
[
'message' => 'Failed to fetch data',
'error' => $response->get_error_message(),
],
500
);
}

// Get the response body.
$data = wp_remote_retrieve_body( $response );

// Check if decode was successful.
if ( null === $data ) {
return new WP_REST_Response(
[
'message' => 'Error getting body',
],
500
);
}

// Create a WP_REST_Response object.
$rest_response = new WP_REST_Response( $data );

// Set status code from the original HTTP response.
$rest_response->set_status( wp_remote_retrieve_response_code( $response ) );

Check failure on line 281 in src/class-service.php

View workflow job for this annotation

GitHub Actions / code-quality / phpstan PHP 8.1

Parameter #1 $code of method WP_HTTP_Response::set_status() expects int, int|string given.

// Set headers.
$headers = wp_remote_retrieve_headers( $response );
foreach ( $headers as $name => $value ) {
$rest_response->header( $name, $value );
}
$rest_response->header( 'X-Proxied-By', 'wp-proxy-service' );

return rest_ensure_response( $rest_response );
}

/**
Expand Down

0 comments on commit e570410

Please sign in to comment.