| 1 |
<?php |
| 2 |
|
| 3 |
namespace Hostinger\Rest; |
| 4 |
|
| 5 |
use Hostinger\Cdn\CachePurger; |
| 6 |
use WP_Error; |
| 7 |
use WP_Http; |
| 8 |
use WP_REST_Request; |
| 9 |
use WP_REST_Response; |
| 10 |
|
| 11 |
defined( 'ABSPATH' ) || exit; |
| 12 |
|
| 13 |
class CacheRoutes { |
| 14 |
private const ERROR_STATUSES = array( |
| 15 |
'hostinger_cdn_purge_failed' => WP_Http::BAD_GATEWAY, |
| 16 |
'hostinger_cdn_no_software_id' => WP_Http::CONFLICT, |
| 17 |
); |
| 18 |
|
| 19 |
private CachePurger $cache_purger; |
| 20 |
|
| 21 |
public function __construct( CachePurger $cache_purger ) { |
| 22 |
$this->cache_purger = $cache_purger; |
| 23 |
} |
| 24 |
|
| 25 |
/** PHPCS:disable Generic.CodeAnalysis.UnusedFunctionParameter.Found */ |
| 26 |
public function clear_cache( WP_REST_Request $request ): WP_REST_Response|WP_Error { |
| 27 |
$result = $this->cache_purger->purge_all(); |
| 28 |
|
| 29 |
if ( is_wp_error( $result ) ) { |
| 30 |
return $this->error_response( $result ); |
| 31 |
} |
| 32 |
|
| 33 |
$response = new WP_REST_Response( array( 'data' => $result ) ); |
| 34 |
|
| 35 |
$response->set_headers( array( 'Cache-Control' => 'no-store' ) ); |
| 36 |
$response->set_status( WP_Http::OK ); |
| 37 |
|
| 38 |
return $response; |
| 39 |
} |
| 40 |
/** PHPCS:enable */ |
| 41 |
|
| 42 |
private function error_response( WP_Error $error ): WP_Error { |
| 43 |
$code = $error->get_error_code(); |
| 44 |
|
| 45 |
return new WP_Error( |
| 46 |
$code, |
| 47 |
$error->get_error_message(), |
| 48 |
array( 'status' => self::ERROR_STATUSES[ $code ] ?? WP_Http::INTERNAL_SERVER_ERROR ) |
| 49 |
); |
| 50 |
} |
| 51 |
} |
| 52 |
|