| 1 |
<?php |
| 2 |
|
| 3 |
namespace ImageOptimization\Classes\Migration\Handlers; |
| 4 |
|
| 5 |
use ImageOptimization\Classes\Image\{ |
| 6 |
Image, |
| 7 |
Image_Meta, |
| 8 |
Image_Query_Builder, |
| 9 |
WP_Image_Meta |
| 10 |
}; |
| 11 |
|
| 12 |
use ImageOptimization\Classes\Migration\Migration; |
| 13 |
use ImageOptimization\Modules\Stats\Classes\Optimization_Stats; |
| 14 |
|
| 15 |
if ( ! defined( 'ABSPATH' ) ) { |
| 16 |
exit; // Exit if accessed directly. |
| 17 |
} |
| 18 |
|
| 19 |
class Fix_Mime_Type extends Migration { |
| 20 |
public static function get_name(): string { |
| 21 |
return 'fix_mime_type'; |
| 22 |
} |
| 23 |
|
| 24 |
public static function run(): bool { |
| 25 |
$query = ( new Image_Query_Builder() ) |
| 26 |
->return_optimized_images() |
| 27 |
->execute(); |
| 28 |
|
| 29 |
if ( ! $query->post_count ) { |
| 30 |
return true; |
| 31 |
} |
| 32 |
|
| 33 |
foreach ( $query->posts as $attachment_id ) { |
| 34 |
$stats = Optimization_Stats::get_image_stats( $attachment_id ); |
| 35 |
$fully_optimized = ( $stats['initial_image_size'] - $stats['current_image_size'] ) <= 0; |
| 36 |
|
| 37 |
if ( $fully_optimized ) { |
| 38 |
$io_meta = new Image_Meta( $attachment_id ); |
| 39 |
$wp_meta = new WP_Image_Meta( $attachment_id ); |
| 40 |
$size_data = $wp_meta->get_size_data( Image::SIZE_FULL ); |
| 41 |
|
| 42 |
if ( |
| 43 |
( ! str_contains( $size_data['file'], '.webp' ) && 'image/webp' === $size_data['mime-type'] ) || |
| 44 |
( ! str_contains( $size_data['file'], '.avif' ) && 'image/avif' === $size_data['mime-type'] ) || |
| 45 |
( ! str_contains( $size_data['file'], '.avif' ) && 'application/octet-stream' === $size_data['mime-type'] ) |
| 46 |
) { |
| 47 |
$original_mime_type = $io_meta->get_original_mime_type( Image::SIZE_FULL ); |
| 48 |
|
| 49 |
foreach ( $wp_meta->get_size_keys() as $size ) { |
| 50 |
$wp_meta |
| 51 |
->set_mime_type( $size, $original_mime_type ) |
| 52 |
->save(); |
| 53 |
} |
| 54 |
} |
| 55 |
} |
| 56 |
} |
| 57 |
|
| 58 |
return true; |
| 59 |
} |
| 60 |
} |
| 61 |
|