| 1 |
<?php |
| 2 |
|
| 3 |
namespace ImageOptimizer\Modules\Optimization\Components; |
| 4 |
|
| 5 |
use ImageOptimizer\Classes\Async_Operation\Async_Operation_Hook; |
| 6 |
use ImageOptimizer\Classes\Image\{ |
| 7 |
Image, |
| 8 |
Image_Meta, |
| 9 |
Image_Optimization_Error_Type, |
| 10 |
Image_Restore, |
| 11 |
Image_Status |
| 12 |
}; |
| 13 |
use ImageOptimizer\Classes\Logger; |
| 14 |
use ImageOptimizer\Modules\Oauth\Classes\Exceptions\Quota_Exceeded_Error; |
| 15 |
use ImageOptimizer\Modules\Optimization\Classes\Optimize_Image; |
| 16 |
use Throwable; |
| 17 |
|
| 18 |
class Single_Optimization { |
| 19 |
/** @async */ |
| 20 |
public function optimize_single_image( int $image_id ) { |
| 21 |
try { |
| 22 |
$oi = new Optimize_Image( |
| 23 |
$image_id, |
| 24 |
'manual', |
| 25 |
); |
| 26 |
|
| 27 |
$oi->optimize(); |
| 28 |
} catch ( Quota_Exceeded_Error $qe ) { |
| 29 |
( new Image_Meta( $image_id ) ) |
| 30 |
->set_status( Image_Status::OPTIMIZATION_FAILED ) |
| 31 |
->set_error_type( Image_Optimization_Error_Type::QUOTA_EXCEEDED ) |
| 32 |
->save(); |
| 33 |
} catch ( Throwable $t ) { |
| 34 |
Logger::log( Logger::LEVEL_ERROR, 'Optimization error. Reason: ' . $t->getMessage() ); |
| 35 |
|
| 36 |
( new Image_Meta( $image_id ) ) |
| 37 |
->set_status( Image_Status::OPTIMIZATION_FAILED ) |
| 38 |
->set_error_type( Image_Optimization_Error_Type::GENERIC ) |
| 39 |
->save(); |
| 40 |
} |
| 41 |
} |
| 42 |
|
| 43 |
/** @async */ |
| 44 |
public function reoptimize_single_image( int $image_id ) { |
| 45 |
try { |
| 46 |
$image = new Image( $image_id ); |
| 47 |
|
| 48 |
if ( $image->can_be_restored() ) { |
| 49 |
Image_Restore::restore( $image_id, true ); |
| 50 |
} |
| 51 |
|
| 52 |
$oi = new Optimize_Image( |
| 53 |
$image_id, |
| 54 |
'manual', |
| 55 |
); |
| 56 |
|
| 57 |
$oi->optimize(); |
| 58 |
} catch ( Quota_Exceeded_Error $qe ) { |
| 59 |
( new Image_Meta( $image_id ) ) |
| 60 |
->set_status( Image_Status::REOPTIMIZING_FAILED ) |
| 61 |
->set_error_type( Image_Optimization_Error_Type::QUOTA_EXCEEDED ) |
| 62 |
->save(); |
| 63 |
} catch ( Throwable $t ) { |
| 64 |
Logger::log( Logger::LEVEL_ERROR, 'Reoptimizing error. Reason: ' . $t->getMessage() ); |
| 65 |
|
| 66 |
( new Image_Meta( $image_id ) ) |
| 67 |
->set_status( Image_Status::REOPTIMIZING_FAILED ) |
| 68 |
->set_error_type( Image_Optimization_Error_Type::GENERIC ) |
| 69 |
->save(); |
| 70 |
} |
| 71 |
} |
| 72 |
|
| 73 |
public function __construct() { |
| 74 |
add_action( Async_Operation_Hook::OPTIMIZE_SINGLE, [ $this, 'optimize_single_image' ] ); |
| 75 |
add_action( Async_Operation_Hook::REOPTIMIZE_SINGLE, [ $this, 'reoptimize_single_image' ] ); |
| 76 |
} |
| 77 |
} |
| 78 |
|