| 1 |
<?php |
| 2 |
|
| 3 |
namespace ImageOptimization\Classes\Migration\Handlers; |
| 4 |
|
| 5 |
use ImageOptimization\Classes\Image\{ |
| 6 |
Image, |
| 7 |
Image_Dimensions, |
| 8 |
Image_Query_Builder, |
| 9 |
WP_Image_Meta, |
| 10 |
}; |
| 11 |
|
| 12 |
use ImageOptimization\Classes\Migration\Migration; |
| 13 |
use Throwable; |
| 14 |
|
| 15 |
if ( ! defined( 'ABSPATH' ) ) { |
| 16 |
exit; // Exit if accessed directly. |
| 17 |
} |
| 18 |
|
| 19 |
class Fix_Avif_With_Zero_Dimensions extends Migration { |
| 20 |
public static function get_name(): string { |
| 21 |
return 'fix_avif_with_zero_dimensions'; |
| 22 |
} |
| 23 |
|
| 24 |
public static function run(): bool { |
| 25 |
$query = ( new Image_Query_Builder() ) |
| 26 |
->set_mime_types( [ 'image/avif', 'application/octet-stream' ] ) |
| 27 |
->return_images_with_non_empty_meta() |
| 28 |
->execute(); |
| 29 |
|
| 30 |
if ( ! $query->post_count ) { |
| 31 |
return true; |
| 32 |
} |
| 33 |
|
| 34 |
foreach ( $query->posts as $attachment_id ) { |
| 35 |
try { |
| 36 |
$wp_meta = new WP_Image_Meta( $attachment_id ); |
| 37 |
$image = new Image( $attachment_id ); |
| 38 |
|
| 39 |
foreach ( $wp_meta->get_size_keys() as $size_key ) { |
| 40 |
if ( 0 === $wp_meta->get_width( $size_key ) || 0 === $wp_meta->get_height( $size_key ) ) { |
| 41 |
$dimensions = Image_Dimensions::get_by_path( $image->get_file_path( $size_key ) ); |
| 42 |
|
| 43 |
$wp_meta |
| 44 |
->set_width( $size_key, $dimensions->width ) |
| 45 |
->set_height( $size_key, $dimensions->height ) |
| 46 |
->save(); |
| 47 |
} |
| 48 |
} |
| 49 |
} catch ( Throwable $t ) { |
| 50 |
continue; |
| 51 |
} |
| 52 |
} |
| 53 |
|
| 54 |
return true; |
| 55 |
} |
| 56 |
} |
| 57 |
|