Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[RW-816] Fix: ensure webp derivative images are deleted #665

Merged
merged 1 commit into from
Oct 15, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions html/modules/custom/reliefweb_utility/reliefweb_utility.module
Original file line number Diff line number Diff line change
Expand Up @@ -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');
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php

namespace Drupal\reliefweb_utility\Entity;

use Drupal\Core\File\Exception\FileException;
use Drupal\imageapi_optimize\Entity\ImageStyleWithPipeline as BaseImageStyleWithPipeline;

/**
* Override of the ImageStyleWithPipeline to also delete webp images.
*/
class ImageStyleWithPipeline extends BaseImageStyleWithPipeline {

/**
* {@inheritdoc}
*/
public function flush($path = NULL) {
$result = parent::flush($path);

// Also delete the webp version of the image if it exists.
if (isset($path)) {
/** @var \Drupal\Core\File\FileSystemInterface $file_system */
$file_system = \Drupal::service('file_system');
$derivative_uri = $this->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;
}

}