| 1 |
<?php |
| 2 |
|
| 3 |
namespace ImageOptimization\Classes\Client; |
| 4 |
|
| 5 |
use Exception; |
| 6 |
use ImageOptimization\Classes\Exceptions\Quota_Exceeded_Error; |
| 7 |
use ImageOptimization\Modules\Optimization\Classes\Exceptions\Bulk_Token_Expired_Error; |
| 8 |
use ImageOptimization\Modules\Optimization\Classes\Exceptions\Image_Already_Optimized_Error; |
| 9 |
use Throwable; |
| 10 |
|
| 11 |
if ( ! defined( 'ABSPATH' ) ) { |
| 12 |
exit; // Exit if accessed directly. |
| 13 |
} |
| 14 |
|
| 15 |
class Client_Response { |
| 16 |
private array $known_errors; |
| 17 |
/** |
| 18 |
* @var mixed |
| 19 |
*/ |
| 20 |
private $response; |
| 21 |
|
| 22 |
/** |
| 23 |
* @throws Throwable|Quota_Exceeded_Error|Bulk_Token_Expired_Error|Image_Already_Optimized_Error |
| 24 |
*/ |
| 25 |
public function handle() { |
| 26 |
if ( ! is_wp_error( $this->response ) ) { |
| 27 |
return $this->response; |
| 28 |
} |
| 29 |
|
| 30 |
$message = $this->response->get_error_message(); |
| 31 |
|
| 32 |
if ( isset( $this->known_errors[ $message ] ) ) { |
| 33 |
throw $this->known_errors[ $message ]; |
| 34 |
} |
| 35 |
|
| 36 |
throw new Exception( $message ); |
| 37 |
} |
| 38 |
|
| 39 |
public function __construct( $response ) { |
| 40 |
$this->known_errors = [ |
| 41 |
'user reached limit' => new Quota_Exceeded_Error( esc_html__( 'Plan quota reached', 'image-optimization' ) ), |
| 42 |
'Bulk token expired' => new Bulk_Token_Expired_Error( esc_html__( 'Bulk token expired', 'image-optimization' ) ), |
| 43 |
'Image already optimized' => new Image_Already_Optimized_Error( esc_html__( 'Image already optimized', 'image-optimization' ) ), |
| 44 |
]; |
| 45 |
$this->response = $response; |
| 46 |
} |
| 47 |
} |
| 48 |
|