Return a token with the name of a single guest

This commit is contained in:
Oliver Davies 2025-05-29 23:38:09 +01:00
parent 52c5eda4a5
commit 487190cb12
7 changed files with 215 additions and 0 deletions

View file

@ -2,7 +2,10 @@
declare(strict_types=1);
use Drupal\Core\Render\BubbleableMetadata;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\node\NodeInterface;
use Drupal\taxonomy\TermInterface;
/**
* @param array<non-empty-string, array<non-empty-string, array{}>> $links
@ -23,3 +26,66 @@ function opd_podcast_node_links_alter(array &$links, NodeInterface $entity, arra
$links['#attributes']['class'][] = 'm-0';
$links['#attributes']['class'][] = 'p-0';
}
/**
* Implements hook_token_info().
*
* @return array{tokens: array<non-empty-string, array{description: TranslatableMarkup, name: TranslatableMarkup}[]>, types: array<non-empty-string, array{description: TranslatableMarkup, name: TranslatableMarkup}>}
*/
function opd_podcast_token_info(): array {
$tokens = [];
$type = [
'description' => t('Tokens related to podcasts.'),
'name' => t('Podcasts'),
];
$tokens['guest-names'] = [
'description' => t('The names of the guests on a podcast episode.'),
'name' => t('Guest names'),
];
return [
'tokens' => [
'opd-podcast' => $tokens,
],
'types' => [
'opd-podcast' => $type,
],
];
}
/**
* Implements hook_tokens().
*
* @param array<non-empty-string, non-empty-string> $tokens
* @param array<non-empty-string, mixed> $data
* @param array<non-empty-string, mixed> $options
*
* @return array<non-empty-string, mixed>
*/
function opd_podcast_tokens(string $type, array $tokens, array $data, array $options, BubbleableMetadata $bubbleableMetadata) : array {
$replacements = [];
if ($type === 'opd-podcast') {
foreach ($tokens as $name => $original) {
switch ($name) {
case 'guest-names':
$node = $data['node'] ?? NULL;
assert($node instanceof NodeInterface);
assert($node->hasField('field_podcast_guests'));
$guests = $node->get('field_podcast_guests')->referencedEntities();
assert(is_array($guests));
assert(!is_null($guests[0]));
assert($guests[0] instanceof TermInterface);
$replacements[$original] = $guests[0]->label();
break;
}
}
}
return $replacements;
}