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

UHF-10973: Cache in _hdbt_set_image_style #1115

Merged
merged 1 commit into from
Nov 20, 2024
Merged
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
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
Loading