From 3809d5a02fe6d0b535cbb0dbfc39041349dbff78 Mon Sep 17 00:00:00 2001 From: Oliver Davies Date: Wed, 16 Sep 2020 00:38:19 +0100 Subject: [PATCH] Add token for getting the number of talks given Add a new custom token, `[opdavies_talks:talk_count]`, that replaces the placeholder text with the talk count value from the `TalkCounter` service. References #31 --- .../custom/talks/opdavies_talks.module | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/web/modules/custom/talks/opdavies_talks.module b/web/modules/custom/talks/opdavies_talks.module index 4bd265c..aeecccf 100644 --- a/web/modules/custom/talks/opdavies_talks.module +++ b/web/modules/custom/talks/opdavies_talks.module @@ -8,7 +8,9 @@ declare(strict_types=1); use Drupal\Core\Entity\EntityTypeInterface; +use Drupal\Core\Render\BubbleableMetadata; use Drupal\discoverable_entity_bundle_classes\Storage\Node\NodeStorage; +use Drupal\opdavies_talks\Service\TalkCounter; use Drupal\opdavies_talks\Service\TalkDateUpdater; /** @@ -43,3 +45,41 @@ function opdavies_talks_entity_type_build(array &$entityTypes): void { $entityTypes['node']->setStorageClass(NodeStorage::class); } } + +/** + * Implements hook_token_info(). + */ +function opdavies_talks_token_info(): array { + $info = []; + + $info['types']['opdavies_talks'] = [ + 'name' => t('Oliver Davies Talks'), + 'description' => t('Custom tokens for the Oliver Davies Talks module.'), + ]; + + $info['tokens']['opdavies_talks']['talk_count'] = 'ddd'; + + return $info; +} + +/** + * Implements hook_tokens(). + */ +function opdavies_talks_tokens(string $type, array $tokens, array $data, array $options, BubbleableMetadata $bubbleableMetadata): array { + $replacements = []; + + if ($type == 'opdavies_talks') { + /** @var TalkCounter $talkCounter */ + $talkCounter = Drupal::service(TalkCounter::class); + + foreach ($tokens as $name => $original) { + switch ($name) { + case 'talk_count': + $replacements[$original] = $talkCounter->getCount(); + break; + } + } + } + + return $replacements; +}