function EntityTypeRepository::getEntityTypeFromClass

Same name and namespace in other branches
  1. 8.9.x core/lib/Drupal/Core/Entity/EntityTypeRepository.php \Drupal\Core\Entity\EntityTypeRepository::getEntityTypeFromClass()
  2. 10 core/lib/Drupal/Core/Entity/EntityTypeRepository.php \Drupal\Core\Entity\EntityTypeRepository::getEntityTypeFromClass()
  3. 11.x core/lib/Drupal/Core/Entity/EntityTypeRepository.php \Drupal\Core\Entity\EntityTypeRepository::getEntityTypeFromClass()

Gets the entity type ID based on the class that is called on.

Compares the class this is called on against the known entity classes and returns the entity type ID of a direct match or a subclass as fallback, to support entity type definitions that were altered.

Parameters

string $class_name: Class name to use for searching the entity type ID.

Return value

string The entity type ID.

Overrides EntityTypeRepositoryInterface::getEntityTypeFromClass

File

core/lib/Drupal/Core/Entity/EntityTypeRepository.php, line 76

Class

EntityTypeRepository
Provides helper methods for loading entity types.

Namespace

Drupal\Core\Entity

Code

public function getEntityTypeFromClass($class_name) {
    // Check the already calculated classes first.
    if (isset($this->classNameEntityTypeMap[$class_name])) {
        return $this->classNameEntityTypeMap[$class_name];
    }
    $same_class = 0;
    $entity_type_id = NULL;
    $definitions = $this->entityTypeManager
        ->getDefinitions();
    foreach ($definitions as $entity_type) {
        if ($entity_type->getOriginalClass() == $class_name || $entity_type->getClass() == $class_name) {
            $entity_type_id = $entity_type->id();
            if ($same_class++) {
                throw new AmbiguousEntityClassException($class_name);
            }
        }
    }
    // If no match was found check if it is a bundle class. This needs to be in
    // a separate loop to avoid false positives, since an entity class can
    // subclass another entity class.
    if (!$entity_type_id) {
        foreach ($definitions as $entity_type) {
            if (is_subclass_of($class_name, $entity_type->getOriginalClass()) || is_subclass_of($class_name, $entity_type->getClass())) {
                $entity_type_id = $entity_type->id();
                if ($same_class++) {
                    throw new AmbiguousBundleClassException($class_name);
                }
            }
        }
    }
    // Return the matching entity type ID if there is one.
    if ($entity_type_id) {
        $this->classNameEntityTypeMap[$class_name] = $entity_type_id;
        return $entity_type_id;
    }
    throw new NoCorrespondingEntityClassException($class_name);
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.