heartbeat_like.tokens.inc 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. /**
  3. * @file
  4. * Token for heartbeat_like.
  5. */
  6. use Drupal\Core\Render\BubbleableMetadata;
  7. /**
  8. * Implements hook_token_info().
  9. */
  10. function heartbeat_like_token_info() {
  11. $types = array();
  12. $tokens = array();
  13. // Flag tokens.
  14. $types['flagcount'] = array(
  15. 'name' => t('Flags count'),
  16. 'description' => t('Tokens related to flag count (heartbeat_like) module.'),
  17. );
  18. $tokens['flagcount']['count'] = array(
  19. 'name' => t('Count'),
  20. 'description' => t('Number of times the flag has been flagged.'),
  21. 'needs-data' => 'flag',
  22. );
  23. return array(
  24. 'types' => $types,
  25. 'tokens' => $tokens,
  26. );
  27. }
  28. /**
  29. * Implements hook_tokens().
  30. */
  31. function heartbeat_like_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {
  32. $replacements = array();
  33. if ($type == 'flagcount') {
  34. foreach ($tokens as $name => $original) {
  35. // Find the desired token by name
  36. switch ($name) {
  37. case 'count':
  38. if (isset($data['flag_id']) && isset($data['entity_id'])) {
  39. // Query the db for the count associated with this entity.
  40. $query = \Drupal::database()->select('flag_counts', 'fc');
  41. $query->fields('fc', ['count']);
  42. $query->condition('fc.flag_id', $data['flag_id']);
  43. $query->condition('fc.entity_id', $data['entity_id']);
  44. $count_db = $query->execute()->fetchAssoc();
  45. if (!isset($count_db['count'])) {
  46. // unset ($replacements[$original]);
  47. $replacements[$original] = "99";
  48. continue 2;
  49. } else {
  50. $replacements[$original] = $count_db['count'];
  51. }
  52. }
  53. break;
  54. }
  55. }
  56. }
  57. // Return the replacements.
  58. return $replacements;
  59. }
  60. /**
  61. * Implements hook_tokens_alter().
  62. * @param array $replacements
  63. * @param array $context
  64. * @param BubbleableMetadata $bubbleable_metadata
  65. */
  66. function heartbeat_like_tokens_alter(array &$replacements, array $context, \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata) {
  67. foreach ($replacements as $key => $replacement) {
  68. if ($key === '[flagcount:count]' && $replacement == 0) {
  69. $replacements[$key] = "";
  70. }
  71. }
  72. }