3 namespace Drupal\Core\Entity;
5 use Drupal\Core\Entity\Exception\AmbiguousEntityClassException;
6 use Drupal\Core\Entity\Exception\NoCorrespondingEntityClassException;
7 use Drupal\Core\StringTranslation\StringTranslationTrait;
10 * Provides helper methods for loading entity types.
12 * @see \Drupal\Core\Entity\EntityTypeManagerInterface
14 class EntityTypeRepository implements EntityTypeRepositoryInterface {
16 use StringTranslationTrait;
19 * The entity type manager.
21 * @var \Drupal\Core\Entity\EntityTypeManagerInterface
23 protected $entityTypeManager;
26 * Contains cached mappings of class names to entity types.
30 protected $classNameEntityTypeMap = [];
33 * Constructs a new EntityTypeRepository.
35 * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
36 * The entity type manager.
38 public function __construct(EntityTypeManagerInterface $entity_type_manager) {
39 $this->entityTypeManager = $entity_type_manager;
45 public function getEntityTypeLabels($group = FALSE) {
47 $definitions = $this->entityTypeManager->getDefinitions();
49 foreach ($definitions as $entity_type_id => $definition) {
51 $options[(string) $definition->getGroupLabel()][$entity_type_id] = $definition->getLabel();
54 $options[$entity_type_id] = $definition->getLabel();
59 foreach ($options as &$group_options) {
60 // Sort the list alphabetically by group label.
61 array_multisort($group_options, SORT_ASC, SORT_NATURAL);
64 // Make sure that the 'Content' group is situated at the top.
65 $content = $this->t('Content', [], ['context' => 'Entity type group']);
66 $options = [(string) $content => $options[(string) $content]] + $options;
75 public function getEntityTypeFromClass($class_name) {
76 // Check the already calculated classes first.
77 if (isset($this->classNameEntityTypeMap[$class_name])) {
78 return $this->classNameEntityTypeMap[$class_name];
82 $entity_type_id = NULL;
83 foreach ($this->entityTypeManager->getDefinitions() as $entity_type) {
84 if ($entity_type->getOriginalClass() == $class_name || $entity_type->getClass() == $class_name) {
85 $entity_type_id = $entity_type->id();
87 throw new AmbiguousEntityClassException($class_name);
92 // Return the matching entity type ID if there is one.
93 if ($entity_type_id) {
94 $this->classNameEntityTypeMap[$class_name] = $entity_type_id;
95 return $entity_type_id;
98 throw new NoCorrespondingEntityClassException($class_name);
104 public function clearCachedDefinitions() {
105 $this->classNameEntityTypeMap = [];