Skip to content

Commit

Permalink
Merge 4cbcfc9 into 44f69ad
Browse files Browse the repository at this point in the history
  • Loading branch information
hyrsky authored Mar 6, 2024
2 parents 44f69ad + 4cbcfc9 commit 10bc690
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 3 deletions.
12 changes: 11 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,23 @@ function helfi_tpr_tokens(
$entity = $data[$type];
$replacements = [];

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

$default_image = '';

// Module might not be installed, or it has incompatible version.
if (function_exists('helfi_base_content_get_default_og_image_url')) {
$default_image = helfi_base_content_get_default_og_image_url();
}

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) ?? $default_image;
}
}

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 10bc690

Please sign in to comment.