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