Skip to content

Commit b2e6fa5

Browse files
committed
Fix optimize_image logic for edge cases
Address Copilot feedback: - Early return when no resize needed for PNG/WebP (avoids returning true) - Simplify result handling - editor->save() always returns array - Set changed=true when any save operation occurs
1 parent 1bd3e76 commit b2e6fa5

File tree

1 file changed

+17
-10
lines changed

1 file changed

+17
-10
lines changed

includes/class-attachments.php

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -629,13 +629,21 @@ private static function optimize_image( $file_path ) {
629629
// Check if WebP is supported.
630630
$can_webp = $editor->supports_mime_type( 'image/webp' );
631631

632-
// Determine output format.
632+
// Determine output format and save.
633633
if ( $can_webp ) {
634+
// Convert to WebP.
634635
$new_path = \preg_replace( '/\.[^.]+$/', '.webp', $file_path );
635636
$result = $editor->save( $new_path, 'image/webp' );
636637
} elseif ( \in_array( $mime_type, array( 'image/png', 'image/webp' ), true ) ) {
637638
// Keep original format for potentially transparent images when WebP not available.
638-
$result = $needs_resize ? $editor->save( $file_path ) : true;
639+
if ( ! $needs_resize ) {
640+
// No changes needed.
641+
return array(
642+
'path' => $file_path,
643+
'changed' => false,
644+
);
645+
}
646+
$result = $editor->save( $file_path );
639647
} else {
640648
// Convert to JPEG when WebP not available.
641649
$new_path = \preg_replace( '/\.[^.]+$/', '.jpg', $file_path );
@@ -649,18 +657,17 @@ private static function optimize_image( $file_path ) {
649657
);
650658
}
651659

652-
// If format changed, delete the original.
653-
if ( is_array( $result ) && isset( $result['path'] ) && $result['path'] !== $file_path ) {
660+
// Handle result - $result is always an array from $editor->save().
661+
$result_path = $result['path'] ?? $file_path;
662+
663+
// If path changed (format conversion), delete the original file.
664+
if ( $result_path !== $file_path ) {
654665
\wp_delete_file( $file_path );
655-
return array(
656-
'path' => $result['path'],
657-
'changed' => true,
658-
);
659666
}
660667

661668
return array(
662-
'path' => $file_path,
663-
'changed' => $needs_resize,
669+
'path' => $result_path,
670+
'changed' => true,
664671
);
665672
}
666673

0 commit comments

Comments
 (0)