Prevent DivisionByZeroError in getThumbnailSizes (#130)

This commit is contained in:
CosmicAlpha 2024-09-13 06:26:06 +08:00 committed by GitHub
parent 0e551d714d
commit 5736d9bfe1
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -101,6 +101,33 @@ class PortableInfoboxImagesHelper {
* @return array [ 'width' => int, 'height' => int ]
*/
public function getThumbnailSizes( $preferredWidth, $maxHeight, $originalWidth, $originalHeight ) {
// Prevent division by zero by ensuring width and height are valid
if ( $originalWidth == 0 && $originalHeight == 0 ) {
// Return default sizes if both original dimensions are zero
return [ 'height' => 0, 'width' => 0 ];
}
// Handle case where only the original width is zero
if ( $originalWidth == 0 ) {
$height = min( $maxHeight, $originalHeight );
// No width can be calculated
return [ 'height' => round( $height ), 'width' => 0 ];
}
// Handle case where only the original height is zero
if ( $originalHeight == 0 ) {
$width = min( $preferredWidth, $originalWidth );
// No height can be calculated
return [ 'height' => 0, 'width' => round( $width ) ];
}
// Prevent issues with invalid maxHeight or preferredWidth
if ( $preferredWidth == 0 || $maxHeight == 0 ) {
// If either maxHeight or preferredWidth is zero, return the original dimensions
return [ 'height' => $originalHeight, 'width' => $originalWidth ];
}
// Standard aspect ratio handling if all dimensions are valid
if ( ( $originalHeight / $originalWidth ) > ( $maxHeight / $preferredWidth ) ) {
$height = min( $maxHeight, $originalHeight );
$width = min( $preferredWidth, $height * $originalWidth / $originalHeight );