TokenEntityMapper.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. namespace Drupal\token;
  3. use Drupal\Core\Entity\EntityTypeManagerInterface;
  4. use Drupal\Core\Extension\ModuleHandlerInterface;
  5. /**
  6. * Service to provide mappings between entity and token types.
  7. *
  8. * Why do we need this? Because when the token API was moved to core we did not
  9. * reuse the entity type as the base name for taxonomy terms and vocabulary
  10. * tokens.
  11. */
  12. class TokenEntityMapper implements TokenEntityMapperInterface {
  13. /**
  14. * @var \Drupal\Core\Entity\EntityTypeManagerInterface
  15. */
  16. protected $entityTypeManager;
  17. /**
  18. * @var \Drupal\Core\Extension\ModuleHandlerInterface
  19. */
  20. protected $moduleHandler;
  21. /**
  22. * @var array
  23. */
  24. protected $entityMappings;
  25. public function __construct(EntityTypeManagerInterface $entity_type_manager, ModuleHandlerInterface $module_handler) {
  26. $this->entityTypeManager = $entity_type_manager;
  27. $this->moduleHandler = $module_handler;
  28. }
  29. /**
  30. * {@inheritdoc}
  31. */
  32. public function getEntityTypeMappings() {
  33. if (empty($this->entityMappings)) {
  34. foreach ($this->entityTypeManager->getDefinitions() as $entity_type => $info) {
  35. $this->entityMappings[$entity_type] = $info->get('token_type') ?: $entity_type;
  36. }
  37. // Allow modules to alter the mapping array.
  38. $this->moduleHandler->alter('token_entity_mapping', $this->entityMappings);
  39. }
  40. return $this->entityMappings;
  41. }
  42. /**
  43. * {@inheritdoc}
  44. */
  45. function getEntityTypeForTokenType($token_type, $fallback = FALSE) {
  46. if (empty($this->entityMappings)) {
  47. $this->getEntityTypeMappings();
  48. }
  49. $return = array_search($token_type, $this->entityMappings);
  50. return $return !== FALSE ? $return : ($fallback ? $token_type : FALSE);
  51. }
  52. /**
  53. * {@inheritdoc}
  54. */
  55. function getTokenTypeForEntityType($entity_type, $fallback = FALSE) {
  56. if (empty($this->entityMappings)) {
  57. $this->getEntityTypeMappings();
  58. }
  59. return isset($this->entityMappings[$entity_type]) ? $this->entityMappings[$entity_type] : ($fallback ? $entity_type : FALSE);
  60. }
  61. /**
  62. * {@inheritdoc}
  63. */
  64. public function resetInfo() {
  65. $this->entityMappings = NULL;
  66. }
  67. }