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-9712: og image fixes #705

Merged
merged 10 commits into from
Mar 18, 2024
53 changes: 52 additions & 1 deletion documentation/development.md
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,7 @@ The update hook above will re-import all configuration from `helfi_media` module

The `helfi_platform_config.config_update_helper` invokes `hook_rewrite_config_update`, which allows custom modules to react to config re-importing.

##### In this example we would want to override Text paragraph label with a configuration found in my_module.
##### In this example we would want to override Text paragraph label with a configuration found in my_module.

To trigger the `hook_rewrite_config_update`, implement the hook to your `my_module.module`:
```php
Expand All @@ -254,3 +254,54 @@ label: Teksti (ylikirjoitettu)
```


## Tokens

Helfi platform config implements `hook_tokens()`. With the help of `helfi_platform_config.og_image_manager` service, it provides `[*:shareable-image]` token. Modules may implement services that handle this token for their entity types.

Modules that use this system should still implement `hook_tokens_info` to provide information about the implemented token.

### Defining image builder service

Add a new service:

```yml
# yourmodule/yourmodule.services.yml
yourmodule.og_image.your_entity_type:
class: Drupal\yourmodule\Token\YourEntityImageBuilder
arguments: []
tags:
- { name: helfi_platform_config.og_image_builder, priority: 100 }
```

```php
# yourmodule/src/Token/YourEntityImageBuilder.php
<?php

declare(strict_types=1);

namespace Drupal\yourmodule\Token;

use Drupal\helfi_platform_config\Token\OGImageBuilderInterface;

/**
* Handles token hooks.
*/
final class YourEntityImageBuilder implements OGImageBuilderInterface {

/**
* {@inheritDoc}
*/
public function applies(EntityInterface $entity): bool {
return $entity instanceof YourEntity;
}

/**
* {@inheritDoc}
*/
public function buildUrl(EntityInterface $entity): ?string {
assert($entity instanceof YourEntity);
return $entity->field_image->entity->getFileUri();
}

}
```
Binary file added fixtures/og-global-sv.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added fixtures/og-global.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
41 changes: 0 additions & 41 deletions helfi_platform_config.module
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Field\FieldConfigBase;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Link;
use Drupal\Core\Render\BubbleableMetadata;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Url;
Expand Down Expand Up @@ -289,17 +288,6 @@ function helfi_platform_config_block_access(Block $block, $operation, AccountInt
return AccessResult::neutral();
}

/**
* Implements hook_token_info().
*/
function helfi_platform_config_token_info() : array {
$info['tokens']['site']['page-title-suffix'] = [
'name' => t('Page title suffix'),
'description' => t('Official suffix for page title.'),
];
return $info;
}

/**
* Grants permissions for given role.
*
Expand Down Expand Up @@ -337,35 +325,6 @@ function helfi_platform_config_remove_permissions_from_all_roles(array $permissi
}
}

/**
* Implements hook_tokens().
*/
function helfi_platform_config_tokens(
$type,
$tokens,
array $data,
array $options,
BubbleableMetadata $bubbleable_metadata
): array {
$replacements = [];

foreach ($tokens as $name => $original) {
if ($name === 'page-title-suffix') {
$language = Drupal::languageManager()
->getCurrentLanguage(LanguageInterface::TYPE_INTERFACE);

$replacements[$original] = match ($language->getId()) {
'fi' => 'Helsingin kaupunki',
'sv' => 'Helsingfors stad',
'ru' => 'Гopoд Xeльcинки',
default => 'City of Helsinki',
};
}
}

return $replacements;
}

/**
* Implements hook_system_breadcrumb_alter().
*/
Expand Down
16 changes: 16 additions & 0 deletions helfi_platform_config.services.yml
Original file line number Diff line number Diff line change
Expand Up @@ -60,3 +60,19 @@ services:
arguments:
- 'helfi_platform_config'

helfi_platform_config.og_image_manager:
class: Drupal\helfi_platform_config\Token\OGImageManager
arguments:
- '@module_handler'
- '@file_url_generator'
tags:
- { name: service_collector, call: add, tag: helfi_platform_config.og_image_builder }

helfi_platform_config.og_image.default:
class: Drupal\helfi_platform_config\Token\DefaultImageBuilder
arguments:
- '@module_handler'
- '@language_manager'
- '@file_url_generator'
tags:
- { name: helfi_platform_config.og_image_builder, priority: -100 }
120 changes: 120 additions & 0 deletions helfi_platform_config.tokens.inc
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
<?php

/**
* @file
* Contains token data for helfi api base.
*/

declare(strict_types=1);

use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Render\BubbleableMetadata;
use Drupal\paragraphs\ParagraphInterface;

/**
* Implements hook_token_info().
*/
function helfi_platform_config_token_info() : array {
$info['tokens']['site']['shareable-image'] = [
'name' => t('Default OG Image'),
'description' => t('Default OG image is used as a default thumbnail in social networks and other services.'),
];
$info['tokens']['node']['shareable-image'] = [
'name' => t('Shareable image'),
'description' => t('Shareable image is used as a thumbnail in social networks and other services.'),
];
$info['tokens']['site']['page-title-suffix'] = [
'name' => t('Page title suffix'),
'description' => t('Official suffix for page title.'),
];

$info['tokens']['node']['lead-in'] = [
'name' => t('Lead in'),
'description' => t(
'Lead in will try to use the hero paragraph description if it exists. If not, it will use the node lead in field.'
),
];
return $info;
}

/**
* Implements hook_tokens().
*
* @see \Drupal\helfi_platform_config\Token\OGImageManager
*/
function helfi_platform_config_tokens(
$type,
$tokens,
array $data,
array $options,
BubbleableMetadata $bubbleable_metadata
) : array {
$replacements = [];

foreach ($tokens as $name => $original) {
if ($name === 'shareable-image') {
$entity = $data[$type] ?? NULL;

if ($entity === NULL || $entity instanceof EntityInterface) {
/** @var \Drupal\helfi_platform_config\Token\OGImageManager $image_manager */
$image_manager = \Drupal::service('helfi_platform_config.og_image_manager');

$replacements[$original] = $image_manager->buildUrl($entity);
}
}
elseif ($name === 'page-title-suffix') {
$language = Drupal::languageManager()
->getCurrentLanguage(LanguageInterface::TYPE_INTERFACE);

$replacements[$original] = match ($language->getId()) {
'fi' => 'Helsingin kaupunki',
'sv' => 'Helsingfors stad',
'ru' => 'Гopoд Xeльcинки',
default => 'City of Helsinki',
};
}
// Custom token for lead in.
elseif ($name === 'lead-in' && !empty($data['node'])) {
/** @var \Drupal\node\NodeInterface $node */
$node = $data['node'];
$lead_in_text = '';

// Check if lead in field exists.
if (
$node->hasField('field_lead_in') &&
!$node?->get('field_lead_in')?->isEmpty()
) {
// Use lead in field as lead in text.
$lead_in_text = $node->get('field_lead_in')->value;
}

// Check if hero paragraph and hero paragraph description exists.
if (
$node->hasField('field_hero') &&
!$node->get('field_hero')?->first()?->isEmpty()
) {
// Get hero paragraph.
$hero = $node->get('field_hero')
?->first()
?->get('entity')
?->getTarget()
?->getValue();

if (
$hero instanceof ParagraphInterface &&
$hero->hasField('field_hero_desc') &&
!$hero->get('field_hero_desc')->isEmpty()
) {
// Use hero paragraph description as lead in text.
$lead_in_text = $hero->get('field_hero_desc')->value;
}
}

// Add lead in text to replacements.
$replacements[$original] = $lead_in_text;
}
}

return $replacements;
}
Loading
Loading