Skip to content

Commit

Permalink
Use image style for og images
Browse files Browse the repository at this point in the history
  • Loading branch information
hyrsky committed Mar 6, 2024
1 parent 44f69ad commit d209756
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
5 changes: 4 additions & 1 deletion helfi_tpr.tokens.inc
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use Drupal\Core\Render\BubbleableMetadata;
use Drupal\helfi_tpr\Entity\Service;
use Drupal\helfi_tpr\Entity\Unit;
use Drupal\image\Entity\ImageStyle;

/**
* Implements hook_token_info().
Expand Down Expand Up @@ -80,14 +81,16 @@ function helfi_tpr_tokens(
$entity = $data[$type];
$replacements = [];

$image_style = ImageStyle::load('og_image');

foreach ($tokens as $name => $original) {
if ($name === 'label') {
$replacements[$original] = $entity->label();
}

if ($entity instanceof Unit) {
if ($name === 'picture') {
$replacements[$original] = $entity->getPictureUrl();
$replacements[$original] = $entity->getPictureUrl($image_style);
}
}

Expand Down
26 changes: 24 additions & 2 deletions src/Entity/Unit.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\image\Entity\ImageStyle;
use Webmozart\Assert\Assert;

/**
Expand Down Expand Up @@ -149,20 +150,41 @@ protected function getServiceIndex(Service $service) {
/**
* Gets the picture url.
*
* @param \Drupal\image\Entity\ImageStyle|null $imageStyle
* URL image style. Original image is returned if style is NULL.
*
* @return string|null
* The picture url.
*/
public function getPictureUrl() : ? string {
public function getPictureUrl(?ImageStyle $imageStyle = NULL) : ? string {
/** @var \Drupal\media\MediaInterface $picture_url */
$picture_url = $this->get('picture_url_override')->entity;

// Fallback to default picture url if override is not set.
if (!$picture_url) {
return $this->get('picture_url')->value;
$url = $this->get('picture_url')->value;

// Run image url through imagecache_external so that we
// can apply image style.
if ($imageStyle) {
$image_path = imagecache_external_generate_path($url);

if ($image_path) {
return $imageStyle->buildUrl($image_path);
}

return NULL;
}

return $url;
}

if ($file = $picture_url->get('field_media_image')->entity) {
/** @var \Drupal\file\FileInterface $file */
if ($imageStyle) {
return $imageStyle->buildUrl($file->getFileUri());
}

try {
return $file->createFileUrl(FALSE) ?: NULL;
}
Expand Down

0 comments on commit d209756

Please sign in to comment.