MatcherTokensTrait.php 1.8 KB

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