Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
CRAP
0.00% covered (danger)
0.00%
0 / 1
Relay_Response
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
30
0.00% covered (danger)
0.00%
0 / 1
 relay_response
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
30
1<?php
2/**
3 * Shared helper for the podcast REST proxy endpoints: relays a
4 * `Connection\Client` response back to the local REST client.
5 *
6 * @package automattic/jetpack-podcast
7 */
8
9namespace Automattic\Jetpack\Podcast;
10
11use WP_Error;
12use WP_REST_Response;
13
14/**
15 * Used by the wpcom/v2 proxy controllers (Podcast_Stats_Endpoint,
16 * Podcast_Distribution_Endpoint, Posts_To_Podcast_Endpoint) to round-trip the
17 * upstream wpcom response: preserves status code and decodes the JSON body so
18 * `apiFetch` on the client surfaces 4xx/5xx errors with their `{code, message}`
19 * payloads intact.
20 */
21trait Relay_Response {
22
23    /**
24     * Relay an upstream Connection\Client response back to the local REST client.
25     * Preserves the upstream HTTP status code so 4xx/5xx mappings flow through.
26     *
27     * @param array|WP_Error $response The raw response from Connection\Client.
28     *
29     * @return WP_REST_Response|WP_Error
30     */
31    private function relay_response( $response ) {
32        if ( is_wp_error( $response ) ) {
33            return $response;
34        }
35
36        $code    = (int) wp_remote_retrieve_response_code( $response );
37        $body    = wp_remote_retrieve_body( $response );
38        $decoded = json_decode( $body, true );
39
40        $rest_response = rest_ensure_response( null === $decoded ? $body : $decoded );
41        if ( $code >= 100 && $code < 600 ) {
42            $rest_response->set_status( $code );
43        }
44        return $rest_response;
45    }
46}