matomo.tokens.inc 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. /**
  3. * @file
  4. * Builds placeholder replacement tokens for user-related data.
  5. */
  6. use Drupal\Component\Utility\Html;
  7. use Drupal\Core\Render\BubbleableMetadata;
  8. /**
  9. * Implements hook_token_info().
  10. */
  11. function matomo_token_info() {
  12. $user['matomo-role-names'] = [
  13. 'name' => t('User role names'),
  14. 'description' => t('The role names the user account is a member of as comma separated list.'),
  15. 'needs-data' => 'user',
  16. ];
  17. $user['matomo-role-ids'] = [
  18. 'name' => t('User role ids'),
  19. 'description' => t('The role ids the user account is a member of as comma separated list.'),
  20. 'needs-data' => 'user',
  21. ];
  22. return [
  23. 'tokens' => ['user' => $user],
  24. ];
  25. }
  26. /**
  27. * Implements hook_tokens().
  28. */
  29. function matomo_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {
  30. $sanitize = !empty($options['sanitize']);
  31. $replacements = [];
  32. if ($type == 'user' && !empty($data['user'])) {
  33. $account = $data['user'];
  34. foreach ($tokens as $name => $original) {
  35. switch ($name) {
  36. // Basic user account information.
  37. case 'matomo-role-names':
  38. $names = implode(',', $account->getRoles());
  39. $replacements[$original] = $sanitize ? Html::escape($names) : $names;
  40. $bubbleable_metadata->addCacheableDependency($account);
  41. break;
  42. case 'matomo-role-ids':
  43. $ids = implode(',', array_keys($account->getRoles()));
  44. $replacements[$original] = $sanitize ? Html::escape($ids) : $ids;
  45. $bubbleable_metadata->addCacheableDependency($account);
  46. break;
  47. }
  48. }
  49. }
  50. return $replacements;
  51. }