Skip to content

Commit

Permalink
Do not serve WebP images that are larger than the original
Browse files Browse the repository at this point in the history
The current code assumes the .webp is always smaller, but occasionally it isn't. Optimiser plugins may report this as "already optimised" or similar.
  • Loading branch information
Roy-Orbison authored Aug 29, 2023
1 parent 68b2aa2 commit 858e9ad
Showing 1 changed file with 10 additions and 4 deletions.
14 changes: 10 additions & 4 deletions inc/Addon/WebP/Subscriber.php
Original file line number Diff line number Diff line change
Expand Up @@ -435,14 +435,20 @@ private function url_to_webp( $url, $extensions ) {

if ( $this->filesystem->exists( $src_path_webp ) ) {
// File name: image.jpg => image.webp.
return preg_replace( '@\.' . $src_url['extension'] . '$@', '.webp', $src_url['src'] ) . $src_url['query'];
$src_url_webp = preg_replace( '@\.' . $src_url['extension'] . '$@', '.webp', $src_url['src'] ) . $src_url['query'];
} else if ( $this->filesystem->exists( $src_path_webp = $src_path . '.webp' ) ) {

Check notice on line 439 in inc/Addon/WebP/Subscriber.php

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

inc/Addon/WebP/Subscriber.php#L439

Assignments must be the first block of code on a line

Check notice on line 439 in inc/Addon/WebP/Subscriber.php

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

inc/Addon/WebP/Subscriber.php#L439

Usage of ELSE IF is discouraged; use ELSEIF instead

Check notice on line 439 in inc/Addon/WebP/Subscriber.php

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

inc/Addon/WebP/Subscriber.php#L439

Variable assignment found within a condition. Did you mean to do a comparison?
// File name: image.jpg => image.jpg.webp.
$src_url_webp = $src_url['src'] . '.webp' . $src_url['query'];
} else {
// No webp exists

Check notice on line 443 in inc/Addon/WebP/Subscriber.php

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

inc/Addon/WebP/Subscriber.php#L443

Inline comments must end in full-stops, exclamation marks, or question marks
return false;
}

if ( $this->filesystem->exists( $src_path . '.webp' ) ) {
// File name: image.jpg => image.jpg.webp.
return $src_url['src'] . '.webp' . $src_url['query'];
if ( $this->filesystem->size( $src_path_webp ) < $this->filesystem->size( $src_path ) ) {
return $src_url_webp;
}

// The webp isn't smaller than the original, so don't use it.
return false;
}

Expand Down

0 comments on commit 858e9ad

Please sign in to comment.