| 1 |
<?php |
| 2 |
|
| 3 |
namespace ImageOptimization\Modules\Optimization\Components; |
| 4 |
|
| 5 |
use ImageOptimization\Classes\Image\Image_Dimensions; |
| 6 |
|
| 7 |
if ( ! defined( 'ABSPATH' ) ) { |
| 8 |
exit; // Exit if accessed directly. |
| 9 |
} |
| 10 |
class Avif_Compatibility { |
| 11 |
public function is_avif_supported(): bool { |
| 12 |
return in_array( 'image/avif', get_allowed_mime_types(), true ); |
| 13 |
} |
| 14 |
|
| 15 |
public function add_to_supported_types( $mime_types ) { |
| 16 |
$mime_types['avif'] = 'image/avif'; |
| 17 |
return $mime_types; |
| 18 |
} |
| 19 |
|
| 20 |
public function add_to_supported_mime_types( $mime_types ) { |
| 21 |
$mime_types['image/avif'] = 'avif'; |
| 22 |
return $mime_types; |
| 23 |
} |
| 24 |
|
| 25 |
public function mark_as_displayable( $result, $path ) { |
| 26 |
if ( str_ends_with( $path, '.avif' ) ) { |
| 27 |
return true; |
| 28 |
} |
| 29 |
|
| 30 |
return $result; |
| 31 |
} |
| 32 |
|
| 33 |
public function fix_avif_images( $metadata, $attachment_id ) { |
| 34 |
if ( empty( $metadata ) ) { |
| 35 |
return $metadata; |
| 36 |
} |
| 37 |
|
| 38 |
$attachment = get_post( $attachment_id ); |
| 39 |
|
| 40 |
if ( ! $attachment || is_wp_error( $attachment ) || 'image/avif' !== $attachment->post_mime_type ) { |
| 41 |
return $metadata; |
| 42 |
} |
| 43 |
|
| 44 |
if ( ( ! empty( $metadata['width'] ) && ( 0 !== $metadata['width'] ) ) && ( ! empty( $metadata['height'] ) && 0 !== $metadata['height'] ) ) { |
| 45 |
return $metadata; |
| 46 |
} |
| 47 |
|
| 48 |
$file = get_attached_file( $attachment_id ); |
| 49 |
|
| 50 |
if ( ! $file ) { |
| 51 |
return $metadata; |
| 52 |
} |
| 53 |
|
| 54 |
$dimensions = Image_Dimensions::get_by_path( $file ); |
| 55 |
|
| 56 |
$metadata['width'] = $dimensions->width; |
| 57 |
$metadata['height'] = $dimensions->height; |
| 58 |
|
| 59 |
if ( empty( $metadata['file'] ) ) { |
| 60 |
$metadata['file'] = _wp_relative_upload_path( $file ); |
| 61 |
} |
| 62 |
|
| 63 |
if ( empty( $metadata['sizes'] ) ) { |
| 64 |
$metadata['sizes'] = []; |
| 65 |
} |
| 66 |
|
| 67 |
return $metadata; |
| 68 |
} |
| 69 |
|
| 70 |
public function __construct() { |
| 71 |
if ( $this->is_avif_supported() ) { |
| 72 |
return; |
| 73 |
} |
| 74 |
|
| 75 |
add_filter( 'upload_mimes', [ $this, 'add_to_supported_types' ] ); |
| 76 |
add_filter( 'mime_types', [ $this, 'add_to_supported_types' ] ); |
| 77 |
add_filter( 'getimagesize_mimes_to_exts', [ $this, 'add_to_supported_mime_types' ] ); |
| 78 |
add_filter( 'file_is_displayable_image', [ $this, 'mark_as_displayable' ], 10, 2 ); |
| 79 |
|
| 80 |
add_filter( 'wp_generate_attachment_metadata', [ $this, 'fix_avif_images' ], 1, 3 ); |
| 81 |
} |
| 82 |
} |
| 83 |
|