MatcherTokensTrait.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. namespace Drupal\linkit;
  3. /**
  4. * Provides friendly methods for matchers using tokens.
  5. */
  6. trait MatcherTokensTrait {
  7. /**
  8. * Inserts a form element with a list of available tokens.
  9. *
  10. * @param array $form
  11. * The form array to append the token list to.
  12. * @param array $types
  13. * An array of token types to use.
  14. */
  15. public function insertTokenList(array &$form, array $types = []) {
  16. if (\Drupal::moduleHandler()->moduleExists('token')) {
  17. // Add the token tree UI.
  18. $form['metadata']['token_tree'] = [
  19. '#theme' => 'token_tree_link',
  20. '#token_types' => $types,
  21. '#dialog' => TRUE,
  22. '#weight' => 10,
  23. ];
  24. }
  25. else {
  26. $token_items = [];
  27. foreach ($this->getAvailableTokens($types) as $type => $tokens) {
  28. foreach ($tokens as $name => $info) {
  29. $token_description = !empty($info['description']) ? $info['description'] : '';
  30. $token_items[$type . ':' . $name] = "[$type:$name]" . ' - ' . $info['name'] . ': ' . $token_description;
  31. }
  32. }
  33. if (count($token_items)) {
  34. $form['metadata']['tokens'] = [
  35. '#type' => 'details',
  36. '#title' => t('Available tokens'),
  37. '#weight' => 10,
  38. ];
  39. $form['metadata']['tokens']['list'] = [
  40. '#theme' => 'item_list',
  41. '#items' => $token_items,
  42. ];
  43. }
  44. }
  45. }
  46. /**
  47. * Gets all available tokens.
  48. *
  49. * @param array $types
  50. * An array of token types to use.
  51. *
  52. * @return array
  53. * An array with available tokens
  54. */
  55. public function getAvailableTokens(array $types = []) {
  56. $info = \Drupal::token()->getInfo();
  57. $available = array_intersect_key($info['tokens'], array_flip($types));
  58. return $available;
  59. }
  60. }