| 1 |
<?php |
| 2 |
/** |
| 3 |
* Raw REST response helper. |
| 4 |
* |
| 5 |
* @package WCPOS\WooCommercePOS\API |
| 6 |
*/ |
| 7 |
|
| 8 |
namespace WCPOS\WooCommercePOS\API; |
| 9 |
|
| 10 |
use WP_REST_Response; |
| 11 |
|
| 12 |
/** |
| 13 |
* Raw_Response class. |
| 14 |
*/ |
| 15 |
class Raw_Response extends WP_REST_Response { |
| 16 |
/** |
| 17 |
* Raw response body. |
| 18 |
* |
| 19 |
* @var string |
| 20 |
*/ |
| 21 |
private $raw_body; |
| 22 |
|
| 23 |
/** |
| 24 |
* Constructor. |
| 25 |
* |
| 26 |
* @param string $body Raw response body. |
| 27 |
*/ |
| 28 |
private function __construct( string $body ) { |
| 29 |
parent::__construct( null, 200 ); |
| 30 |
$this->raw_body = $body; |
| 31 |
} |
| 32 |
|
| 33 |
/** |
| 34 |
* Serve raw bytes from a REST callback. |
| 35 |
* |
| 36 |
* @param string $body Response body. |
| 37 |
* @param string $content_type Content type. |
| 38 |
* @param array $headers Extra headers. |
| 39 |
* |
| 40 |
* @return self |
| 41 |
*/ |
| 42 |
public static function serve( string $body, string $content_type, array $headers = array() ): self { |
| 43 |
$response = new self( $body ); |
| 44 |
$response->header( 'Content-Type', $content_type ); |
| 45 |
|
| 46 |
foreach ( $headers as $name => $value ) { |
| 47 |
$response->header( (string) $name, (string) $value ); |
| 48 |
} |
| 49 |
|
| 50 |
$served = false; |
| 51 |
add_filter( |
| 52 |
'rest_pre_serve_request', |
| 53 |
static function ( $served_result, $result ) use ( $response, &$served ) { |
| 54 |
if ( $served || $result !== $response ) { |
| 55 |
return $served_result; |
| 56 |
} |
| 57 |
$served = true; |
| 58 |
echo $response->get_raw_body(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Raw response bytes. |
| 59 |
|
| 60 |
return true; |
| 61 |
}, |
| 62 |
10, |
| 63 |
2 |
| 64 |
); |
| 65 |
|
| 66 |
return $response; |
| 67 |
} |
| 68 |
|
| 69 |
/** |
| 70 |
* Get the raw response body for tests and direct consumers. |
| 71 |
* |
| 72 |
* @return string |
| 73 |
*/ |
| 74 |
public function get_raw_body(): string { |
| 75 |
return $this->raw_body; |
| 76 |
} |
| 77 |
} |
| 78 |
|