| 1 |
<?php declare(strict_types=1); |
| 2 |
|
| 3 |
namespace MultiSafepay\WooCommerce\Utils; |
| 4 |
|
| 5 |
use WP_REST_Response; |
| 6 |
|
| 7 |
/** |
| 8 |
* Class RestResponseBuilder |
| 9 |
* |
| 10 |
* Shared helper for building REST responses with explicit no-store cache headers. |
| 11 |
* |
| 12 |
* @package MultiSafepay\WooCommerce\Utils |
| 13 |
*/ |
| 14 |
class RestResponseBuilder { |
| 15 |
|
| 16 |
/** |
| 17 |
* Build a REST response with explicit anti-cache headers. |
| 18 |
* |
| 19 |
* @param int $status HTTP status code |
| 20 |
* @param mixed $body Response body |
| 21 |
* @param array $headers Optional associative array of custom headers (e.g., ['Location' => '...', 'Content-Type' => '...']) |
| 22 |
* @return WP_REST_Response |
| 23 |
*/ |
| 24 |
public static function build_response( int $status = 200, $body = 'OK', array $headers = array() ): WP_REST_Response { |
| 25 |
$response = new WP_REST_Response( $body, $status ); |
| 26 |
|
| 27 |
// Set default Content-Type as required by MultiSafepay webhook acknowledgment |
| 28 |
if ( $status < 300 || $status >= 400 ) { |
| 29 |
$response->header( 'Content-Type', 'text/plain; charset=UTF-8' ); |
| 30 |
} |
| 31 |
|
| 32 |
$nocache_headers = function_exists( 'wp_get_nocache_headers' ) |
| 33 |
? wp_get_nocache_headers() |
| 34 |
: array( |
| 35 |
'Expires' => 'Wed, 11 Jan 1984 05:00:00 GMT', |
| 36 |
'Cache-Control' => 'no-cache, must-revalidate, max-age=0, no-store, private', |
| 37 |
); |
| 38 |
|
| 39 |
foreach ( $nocache_headers as $header => $header_value ) { |
| 40 |
if ( 'Last-Modified' === $header ) { |
| 41 |
continue; |
| 42 |
} |
| 43 |
if ( empty( $header_value ) ) { |
| 44 |
continue; |
| 45 |
} |
| 46 |
$response->header( $header, (string) $header_value ); |
| 47 |
} |
| 48 |
|
| 49 |
$response->header( 'Pragma', 'no-cache' ); |
| 50 |
|
| 51 |
// Apply custom headers (can override defaults like Content-Type) |
| 52 |
foreach ( $headers as $header => $header_value ) { |
| 53 |
$response->header( $header, (string) $header_value ); |
| 54 |
} |
| 55 |
|
| 56 |
return $response; |
| 57 |
} |
| 58 |
} |
| 59 |
|