From 58756868d31a5356a30b5b6083e2eb2a3339f014 Mon Sep 17 00:00:00 2001 From: Santeri Hurnanen Date: Wed, 20 Nov 2024 08:43:00 +0200 Subject: [PATCH] UHF-10973: Cache in _hdbt_set_image_style --- hdbt.theme | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/hdbt.theme b/hdbt.theme index 16ed9f9ed..5f2b18c04 100644 --- a/hdbt.theme +++ b/hdbt.theme @@ -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; @@ -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(); } } @@ -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;