diff --git a/modules/webp-uploads/load.php b/modules/webp-uploads/load.php new file mode 100644 index 0000000000..3dbd44f292 --- /dev/null +++ b/modules/webp-uploads/load.php @@ -0,0 +1,40 @@ + 'image/webp' ) ) ) { + return $output_format; + } + + // WebP lossless support is still limited on servers, so only apply to JPEGs. + if ( 'image/jpeg' !== $mime_type ) { + return $output_format; + } + + $output_format['image/jpeg'] = 'image/webp'; + + return $output_format; +} +add_filter( 'image_editor_output_format', 'webp_uploads_filter_image_editor_output_format', 10, 3 ); + diff --git a/tests/modules/webp-uploads/webp-uploads-test.php b/tests/modules/webp-uploads/webp-uploads-test.php new file mode 100644 index 0000000000..943105a9c2 --- /dev/null +++ b/tests/modules/webp-uploads/webp-uploads-test.php @@ -0,0 +1,60 @@ + 'image/webp' ) ) ) { + $expect = array(); + } else { + $expect = array( 'image/jpeg' => 'image/webp' ); + } + + $output_format = apply_filters( 'image_editor_output_format', array(), '', 'image/jpeg' ); + $this->assertEquals( $expect, $output_format ); + } + + /** + * Verify webp-uploads applies filter with a system that supports WebP. + */ + function test_webp_uploads_filter_image_editor_output_format_with_support() { + // Mock a system that supports WebP. + add_filter( 'wp_image_editors', array( $this, 'mock_wp_image_editor_supports' ) ); + $output_format = webp_uploads_filter_image_editor_output_format( array(), '', 'image/jpeg' ); + $this->assertEquals( array( 'image/jpeg' => 'image/webp' ), $output_format ); + } + + /** + * Verify if webp-uploads doesn't apply filter with a system that doesn't support WebP. + */ + function test_webp_uploads_filter_image_editor_output_format_without_support() { + // Mock a system that doesn't support WebP. + add_filter( 'wp_image_editors', array( $this, 'mock_wp_image_editor_doesnt_support' ) ); + $output_format = webp_uploads_filter_image_editor_output_format( array(), '', 'image/jpeg' ); + $this->assertEquals( array(), $output_format ); + } + + /** + * Mock an image editor that supports WebP. + */ + public function mock_wp_image_editor_supports() { + $editors = array( 'WP_Image_Supports_WebP' ); + return $editors; + } + + /** + * Mock an image editor that doesn't support WebP. + */ + public function mock_wp_image_editor_doesnt_support() { + $editors = array( 'WP_Image_Doesnt_Support_WebP' ); + return $editors; + } +} diff --git a/tests/testdata/modules/webp-uploads/class-wp-image-doesnt-support-webp.php b/tests/testdata/modules/webp-uploads/class-wp-image-doesnt-support-webp.php new file mode 100644 index 0000000000..80ac4af4ef --- /dev/null +++ b/tests/testdata/modules/webp-uploads/class-wp-image-doesnt-support-webp.php @@ -0,0 +1,36 @@ +