Skip to content

Commit

Permalink
UHF-10973: Cache in _hdbt_set_image_style
Browse files Browse the repository at this point in the history
  • Loading branch information
hyrsky committed Nov 20, 2024
1 parent 788a852 commit 5875686
Showing 1 changed file with 16 additions and 6 deletions.
22 changes: 16 additions & 6 deletions hdbt.theme
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

declare(strict_types=1);

use Drupal\Core\Cache\Cache;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Template\Attribute;
Expand Down Expand Up @@ -1150,19 +1151,21 @@ function _hdbt_set_image_style(array &$variables, string $entity_type, string $i
$entity->{$image}->entity->hasField('field_media_image') &&
!$entity->{$image}->entity->field_media_image->first()->isEmpty()
) {
/** @var \Drupal\file\FileInterface $file */
$file = $entity->{$image}->entity;
/** @var \Drupal\media\MediaInterface $media */
$media = $entity->{$image}->entity;

// Make sure we load the correct file translation, otherwise
// Make sure we load the correct media translation, otherwise
// hdbt_preprocess_responsive_image_formatter() will receive an empty
// 'altered_image_style' value for translated media entities.
if ($file->hasTranslation($variables['language']->getId())) {
$file = $file->getTranslation($variables['language']->getId());
if ($media->hasTranslation($variables['language']->getId())) {
$media = $media->getTranslation($variables['language']->getId());
}
// Set altered_image_style variable based on modified image style
// for the responsive image preprocesses.
// @phpstan-ignore-next-line
$file->field_media_image->first()->altered_image_style = $image_style;
$media->field_media_image->first()->altered_image_style = $image_style;
// @phpstan-ignore-next-line
$media->field_media_image->first()->altered_cache_tags = $entity->getCacheTags();
}
}

Expand Down Expand Up @@ -1198,6 +1201,13 @@ function hdbt_preprocess_responsive_image_formatter(&$variables): void {
$variables['responsive_image']['#responsive_image_style_id'] = $variables['item']->altered_image_style;
}

if (!empty($variables['item']->altered_cache_tags)) {
$variables['responsive_image']['#cache']['tags'] = Cache::mergeTags(
$variables['item']->altered_cache_tags,
$variables['responsive_image']['#cache']['tags'] ?? []
);
}

$image_style = array_key_exists('#responsive_image_style_id', $variables['responsive_image'])
? $variables['responsive_image']['#responsive_image_style_id']
: NULL;
Expand Down

0 comments on commit 5875686

Please sign in to comment.