From 70f2076fc0a7eb62665505592c471fc0316bfae3 Mon Sep 17 00:00:00 2001 From: orakili Date: Sun, 15 Oct 2023 23:13:39 +0000 Subject: [PATCH] fix: ensure webp derivative images are deleted Refs: RW-816 --- .../reliefweb_utility.module | 20 ++++++++++ .../src/Entity/ImageStyleWithPipeline.php | 39 +++++++++++++++++++ 2 files changed, 59 insertions(+) create mode 100644 html/modules/custom/reliefweb_utility/src/Entity/ImageStyleWithPipeline.php diff --git a/html/modules/custom/reliefweb_utility/reliefweb_utility.module b/html/modules/custom/reliefweb_utility/reliefweb_utility.module index 6178839b5..64f77375f 100644 --- a/html/modules/custom/reliefweb_utility/reliefweb_utility.module +++ b/html/modules/custom/reliefweb_utility/reliefweb_utility.module @@ -89,3 +89,23 @@ function reliefweb_utility_file_presave(FileInterface $file) { } } } + +/** + * Implements hook_entity_type_alter(). + * + * Replace the image style class so we can properly delete webp versions of the + * derivative images because this is not done by image_optimize_webp, notably + * because there is no hook provided for that by the image module. + * + * Normally this runs after the imageapi_optimize_entity_type_alter() due to + * the alphabetical order. + */ +function reliefweb_utility_entity_type_alter(array &$entity_types) { + /** @var \Drupal\Core\Entity\EntityTypeInterface[] $entity_types */ + if (isset($entity_types['image_style'])) { + $image_style = $entity_types['image_style']; + if ($image_style->getClass() === 'Drupal\imageapi_optimize\Entity\ImageStyleWithPipeline') { + $image_style->setClass('Drupal\reliefweb_utility\Entity\ImageStyleWithPipeline'); + } + } +} diff --git a/html/modules/custom/reliefweb_utility/src/Entity/ImageStyleWithPipeline.php b/html/modules/custom/reliefweb_utility/src/Entity/ImageStyleWithPipeline.php new file mode 100644 index 000000000..9a2492d0c --- /dev/null +++ b/html/modules/custom/reliefweb_utility/src/Entity/ImageStyleWithPipeline.php @@ -0,0 +1,39 @@ +buildUri($path); + $derivative_uri_webp = $derivative_uri . '.webp'; + + if (file_exists($derivative_uri_webp)) { + try { + $file_system->delete($derivative_uri_webp); + } + catch (FileException $exception) { + // Ignore failed deletion. + } + } + } + + return $result; + } + +}