class EntityTypeManager

Same name in other branches
  1. 9 core/lib/Drupal/Core/Entity/EntityTypeManager.php \Drupal\Core\Entity\EntityTypeManager
  2. 8.9.x core/lib/Drupal/Core/Entity/EntityTypeManager.php \Drupal\Core\Entity\EntityTypeManager
  3. 11.x core/lib/Drupal/Core/Entity/EntityTypeManager.php \Drupal\Core\Entity\EntityTypeManager

Manages entity type plugin definitions.

Each entity type definition array is set in the entity type's annotation and altered by hook_entity_type_alter().

Do not use hook_entity_type_alter() hook to add information to entity types, unless one of the following is true:

  • You are filling in default values.
  • You need to dynamically add information only in certain circumstances.
  • Your hook needs to run after hook_entity_type_build() implementations.

Use hook_entity_type_build() instead in all other cases.

Hierarchy

Expanded class hierarchy of EntityTypeManager

See also

\Drupal\Core\Entity\Annotation\EntityType

\Drupal\Core\Entity\EntityInterface

\Drupal\Core\Entity\EntityTypeInterface

hook_entity_type_alter()

hook_entity_type_build()

8 files declare their use of EntityTypeManager
CopyTest.php in core/modules/file/tests/src/Kernel/CopyTest.php
EntityReferenceSupportedNewEntitiesConstraintValidatorTest.php in core/modules/workspaces/tests/src/Kernel/EntityReferenceSupportedNewEntitiesConstraintValidatorTest.php
EntityTypeManagerTest.php in core/tests/Drupal/Tests/Core/Entity/EntityTypeManagerTest.php
FileRepositoryTest.php in core/modules/file/tests/src/Kernel/FileRepositoryTest.php
LanguageNegotiationContentEntityTest.php in core/modules/language/tests/src/Unit/Plugin/LanguageNegotiation/LanguageNegotiationContentEntityTest.php

... See full list

1 string reference to 'EntityTypeManager'
core.services.yml in core/core.services.yml
core/core.services.yml
1 service uses EntityTypeManager
entity_type.manager in core/core.services.yml
Drupal\Core\Entity\EntityTypeManager

File

core/lib/Drupal/Core/Entity/EntityTypeManager.php, line 35

Namespace

Drupal\Core\Entity
View source
class EntityTypeManager extends DefaultPluginManager implements EntityTypeManagerInterface {
    
    /**
     * Contains instantiated handlers keyed by handler type and entity type.
     *
     * @var array
     */
    protected $handlers = [];
    
    /**
     * The string translation service.
     *
     * @var \Drupal\Core\StringTranslation\TranslationInterface
     */
    protected $stringTranslation;
    
    /**
     * The class resolver.
     *
     * @var \Drupal\Core\DependencyInjection\ClassResolverInterface
     */
    protected $classResolver;
    
    /**
     * The entity last installed schema repository.
     *
     * @var \Drupal\Core\Entity\EntityLastInstalledSchemaRepositoryInterface
     */
    protected $entityLastInstalledSchemaRepository;
    
    /**
     * Constructs a new Entity plugin manager.
     *
     * @param \Traversable $namespaces
     *   An object that implements \Traversable which contains the root paths
     *   keyed by the corresponding namespace to look for plugin implementations,
     * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
     *   The module handler.
     * @param \Drupal\Core\Cache\CacheBackendInterface $cache
     *   The cache backend to use.
     * @param \Drupal\Core\StringTranslation\TranslationInterface $string_translation
     *   The string translation.
     * @param \Drupal\Core\DependencyInjection\ClassResolverInterface $class_resolver
     *   The class resolver.
     * @param \Drupal\Core\Entity\EntityLastInstalledSchemaRepositoryInterface $entity_last_installed_schema_repository
     *   The entity last installed schema repository.
     * @param \Symfony\Component\DependencyInjection\ContainerInterface|null $container
     *   The service container.
     */
    public function __construct(\Traversable $namespaces, ModuleHandlerInterface $module_handler, CacheBackendInterface $cache, TranslationInterface $string_translation, ClassResolverInterface $class_resolver, EntityLastInstalledSchemaRepositoryInterface $entity_last_installed_schema_repository, ?ContainerInterface $container = NULL) {
        parent::__construct('Entity', $namespaces, $module_handler, 'Drupal\\Core\\Entity\\EntityInterface');
        $this->setCacheBackend($cache, 'entity_type', [
            'entity_types',
        ]);
        $this->alterInfo('entity_type');
        $this->discovery = new AnnotatedClassDiscovery('Entity', $namespaces, 'Drupal\\Core\\Entity\\Annotation\\EntityType');
        $this->stringTranslation = $string_translation;
        $this->classResolver = $class_resolver;
        $this->entityLastInstalledSchemaRepository = $entity_last_installed_schema_repository;
        if ($this->container === NULL) {
            @trigger_error('Calling ' . __METHOD__ . ' without the $container argument is deprecated in drupal:10.3.0 and it will be required in drupal:11.0.0. See https://www.drupal.org/node/3419963', E_USER_DEPRECATED);
            $this->container = \Drupal::getContainer();
        }
    }
    
    /**
     * {@inheritdoc}
     */
    public function processDefinition(&$definition, $plugin_id) {
        
        /** @var \Drupal\Core\Entity\EntityTypeInterface $definition */
        parent::processDefinition($definition, $plugin_id);
        // All link templates must have a leading slash.
        foreach ((array) $definition->getLinkTemplates() as $link_relation_name => $link_template) {
            if ($link_template[0] != '/') {
                throw new InvalidLinkTemplateException("Link template '{$link_relation_name}' for entity type '{$plugin_id}' must start with a leading slash, the current link template is '{$link_template}'");
            }
        }
    }
    
    /**
     * {@inheritdoc}
     */
    protected function findDefinitions() {
        $definitions = $this->getDiscovery()
            ->getDefinitions();
        $this->moduleHandler
            ->invokeAllWith('entity_type_build', function (callable $hook, string $module) use (&$definitions) {
            $hook($definitions);
        });
        foreach ($definitions as $plugin_id => $definition) {
            $this->processDefinition($definition, $plugin_id);
        }
        $this->alterDefinitions($definitions);
        return $definitions;
    }
    
    /**
     * {@inheritdoc}
     */
    public function getDefinition($entity_type_id, $exception_on_invalid = TRUE) {
        if (($entity_type = parent::getDefinition($entity_type_id, FALSE)) && class_exists($entity_type->getClass())) {
            return $entity_type;
        }
        elseif (!$exception_on_invalid) {
            return NULL;
        }
        throw new PluginNotFoundException($entity_type_id, sprintf('The "%s" entity type does not exist.', $entity_type_id));
    }
    
    /**
     * Gets the active definition for a content entity type.
     *
     * @param string $entity_type_id
     *   The entity type ID.
     *
     * @return \Drupal\Core\Entity\EntityTypeInterface
     *   The active entity type definition.
     *
     * @internal
     */
    public function getActiveDefinition($entity_type_id) {
        $definition = $this->entityLastInstalledSchemaRepository
            ->getLastInstalledDefinition($entity_type_id);
        return $definition ?: $this->getDefinition($entity_type_id);
    }
    
    /**
     * {@inheritdoc}
     */
    public function clearCachedDefinitions() {
        parent::clearCachedDefinitions();
        $this->handlers = [];
    }
    
    /**
     * {@inheritdoc}
     */
    public function useCaches($use_caches = FALSE) {
        parent::useCaches($use_caches);
        if (!$use_caches) {
            $this->handlers = [];
            $this->container
                ->get('entity.memory_cache')
                ->reset();
        }
    }
    
    /**
     * {@inheritdoc}
     */
    public function hasHandler($entity_type_id, $handler_type) {
        if ($definition = $this->getDefinition($entity_type_id, FALSE)) {
            return $definition->hasHandlerClass($handler_type);
        }
        return FALSE;
    }
    
    /**
     * {@inheritdoc}
     */
    public function getStorage($entity_type_id) {
        return $this->getHandler($entity_type_id, 'storage');
    }
    
    /**
     * {@inheritdoc}
     */
    public function getListBuilder($entity_type_id) {
        return $this->getHandler($entity_type_id, 'list_builder');
    }
    
    /**
     * {@inheritdoc}
     */
    public function getFormObject($entity_type_id, $operation) {
        if (!($class = $this->getDefinition($entity_type_id, TRUE)
            ->getFormClass($operation))) {
            $handlers = $this->getDefinition($entity_type_id, TRUE)
                ->getHandlerClasses();
            if (!isset($handlers['form'][$operation])) {
                throw new InvalidPluginDefinitionException($entity_type_id, sprintf('The "%s" entity type did not specify a "%s" form class.', $entity_type_id, $operation));
            }
            throw new InvalidPluginDefinitionException($entity_type_id, sprintf('The "%s" form handler of the "%s" entity type specifies a non-existent class "%s".', $operation, $entity_type_id, $handlers['form'][$operation]));
        }
        $form_object = $this->classResolver
            ->getInstanceFromDefinition($class);
        return $form_object->setStringTranslation($this->stringTranslation)
            ->setModuleHandler($this->moduleHandler)
            ->setEntityTypeManager($this)
            ->setOperation($operation);
    }
    
    /**
     * {@inheritdoc}
     */
    public function getRouteProviders($entity_type_id) {
        if (!isset($this->handlers['route_provider'][$entity_type_id])) {
            $route_provider_classes = $this->getDefinition($entity_type_id, TRUE)
                ->getRouteProviderClasses();
            foreach ($route_provider_classes as $type => $class) {
                $this->handlers['route_provider'][$entity_type_id][$type] = $this->createHandlerInstance($class, $this->getDefinition($entity_type_id));
            }
        }
        return $this->handlers['route_provider'][$entity_type_id] ?? [];
    }
    
    /**
     * {@inheritdoc}
     */
    public function getViewBuilder($entity_type_id) {
        return $this->getHandler($entity_type_id, 'view_builder');
    }
    
    /**
     * {@inheritdoc}
     */
    public function getAccessControlHandler($entity_type_id) {
        return $this->getHandler($entity_type_id, 'access');
    }
    
    /**
     * {@inheritdoc}
     */
    public function getHandler($entity_type_id, $handler_type) {
        if (!isset($this->handlers[$handler_type][$entity_type_id])) {
            $definition = $this->getDefinition($entity_type_id);
            $class = $definition->getHandlerClass($handler_type);
            if (!$class) {
                $handlers = $definition->getHandlerClasses();
                if (!isset($handlers[$handler_type])) {
                    throw new InvalidPluginDefinitionException($entity_type_id, sprintf('The "%s" entity type did not specify a %s handler.', $entity_type_id, $handler_type));
                }
                throw new InvalidPluginDefinitionException($entity_type_id, sprintf('The %s handler of the "%s" entity type specifies a non-existent class "%s".', $handler_type, $entity_type_id, $handlers[$handler_type]));
            }
            $this->handlers[$handler_type][$entity_type_id] = $this->createHandlerInstance($class, $definition);
        }
        return $this->handlers[$handler_type][$entity_type_id];
    }
    
    /**
     * {@inheritdoc}
     */
    public function createHandlerInstance($class, ?EntityTypeInterface $definition = NULL) {
        if (is_subclass_of($class, 'Drupal\\Core\\Entity\\EntityHandlerInterface')) {
            $handler = $class::createInstance($this->container, $definition);
        }
        else {
            $handler = new $class($definition);
        }
        if (method_exists($handler, 'setModuleHandler')) {
            $handler->setModuleHandler($this->moduleHandler);
        }
        if (method_exists($handler, 'setStringTranslation')) {
            $handler->setStringTranslation($this->stringTranslation);
        }
        return $handler;
    }
    
    /**
     * Sets the service container.
     *
     * @deprecated in drupal:10.3.0 and is removed from drupal:11.0.0.
     *    Instead, you should pass the container as an argument in the
     *    __construct() method.
     *
     * @see https://www.drupal.org/node/3419963
     */
    public function setContainer(?ContainerInterface $container) : void {
        @trigger_error(__METHOD__ . '() is deprecated in drupal:10.3.0 and is removed from drupal:11.0.0. Instead, you should pass the container as an argument in the __construct() method. See https://www.drupal.org/node/3419963', E_USER_DEPRECATED);
        $this->container = $container;
    }

}

Members

Title Sort descending Deprecated Modifiers Object type Summary Overriden Title Overrides
DefaultPluginManager::$additionalAnnotationNamespaces protected property Additional annotation namespaces.
DefaultPluginManager::$alterHook protected property Name of the alter hook if one should be invoked.
DefaultPluginManager::$cacheKey protected property The cache key.
DefaultPluginManager::$cacheTags protected property An array of cache tags to use for the cached definitions.
DefaultPluginManager::$defaults protected property A set of defaults to be referenced by $this->processDefinition(). 12
DefaultPluginManager::$moduleExtensionList protected property The module extension list.
DefaultPluginManager::$moduleHandler protected property The module handler to invoke the alter hook. 1
DefaultPluginManager::$namespaces protected property An object of root paths that are traversable.
DefaultPluginManager::$pluginDefinitionAnnotationName protected property The name of the annotation that contains the plugin definition.
DefaultPluginManager::$pluginDefinitionAttributeName protected property The name of the attribute that contains the plugin definition.
DefaultPluginManager::$pluginInterface protected property The interface each plugin should implement. 1
DefaultPluginManager::$subdir protected property The subdirectory within a namespace to look for plugins.
DefaultPluginManager::alterDefinitions protected function Invokes the hook to alter the definitions if the alter hook is set. 5
DefaultPluginManager::alterInfo protected function Sets the alter hook name.
DefaultPluginManager::extractProviderFromDefinition protected function Extracts the provider from a plugin definition.
DefaultPluginManager::getCacheContexts public function The cache contexts associated with this object. Overrides CacheableDependencyInterface::getCacheContexts
DefaultPluginManager::getCachedDefinitions protected function Returns the cached plugin definitions of the decorated discovery class.
DefaultPluginManager::getCacheMaxAge public function The maximum age for which this object may be cached. Overrides CacheableDependencyInterface::getCacheMaxAge
DefaultPluginManager::getCacheTags public function The cache tags associated with this object. Overrides CacheableDependencyInterface::getCacheTags
DefaultPluginManager::getDefinitions public function Gets the definition of all plugins for this type. Overrides DiscoveryTrait::getDefinitions 2
DefaultPluginManager::getDiscovery protected function Gets the plugin discovery. Overrides PluginManagerBase::getDiscovery 16
DefaultPluginManager::getFactory protected function Gets the plugin factory. Overrides PluginManagerBase::getFactory
DefaultPluginManager::providerExists protected function Determines if the provider of a definition exists. 5
DefaultPluginManager::setCacheBackend public function Initialize the cache backend.
DefaultPluginManager::setCachedDefinitions protected function Sets a cache of plugin definitions for the decorated discovery class.
DiscoveryCachedTrait::$definitions protected property Cached definitions array. 1
DiscoveryTrait::doGetDefinition protected function Gets a specific plugin definition.
DiscoveryTrait::hasDefinition public function
EntityTypeManager::$classResolver protected property The class resolver.
EntityTypeManager::$entityLastInstalledSchemaRepository protected property The entity last installed schema repository.
EntityTypeManager::$handlers protected property Contains instantiated handlers keyed by handler type and entity type.
EntityTypeManager::$stringTranslation protected property The string translation service.
EntityTypeManager::clearCachedDefinitions public function Clears static and persistent plugin definition caches. Overrides DefaultPluginManager::clearCachedDefinitions
EntityTypeManager::createHandlerInstance public function
EntityTypeManager::findDefinitions protected function Finds plugin definitions. Overrides DefaultPluginManager::findDefinitions
EntityTypeManager::getAccessControlHandler public function
EntityTypeManager::getActiveDefinition public function Gets the active definition for a content entity type.
EntityTypeManager::getDefinition public function Overrides DiscoveryCachedTrait::getDefinition
EntityTypeManager::getFormObject public function
EntityTypeManager::getHandler public function
EntityTypeManager::getListBuilder public function
EntityTypeManager::getRouteProviders public function
EntityTypeManager::getStorage public function
EntityTypeManager::getViewBuilder public function
EntityTypeManager::hasHandler public function
EntityTypeManager::processDefinition public function Performs extra processing on plugin definitions. Overrides DefaultPluginManager::processDefinition
EntityTypeManager::setContainer Deprecated public function Sets the service container.
EntityTypeManager::useCaches public function Disable the use of caches. Overrides DefaultPluginManager::useCaches
EntityTypeManager::__construct public function Constructs a new Entity plugin manager. Overrides DefaultPluginManager::__construct
PluginManagerBase::$discovery protected property The object that discovers plugins managed by this manager.
PluginManagerBase::$factory protected property The object that instantiates plugins managed by this manager.
PluginManagerBase::$mapper protected property The object that returns the preconfigured plugin instance appropriate for a particular runtime condition.
PluginManagerBase::createInstance public function 15
PluginManagerBase::getFallbackPluginId protected function Gets a fallback id for a missing plugin. 6
PluginManagerBase::getInstance public function 6
PluginManagerBase::handlePluginNotFound protected function Allows plugin managers to specify custom behavior if a plugin is not found. 1
UseCacheBackendTrait::$cacheBackend protected property Cache backend instance.
UseCacheBackendTrait::$useCaches protected property Flag whether caches should be used or skipped.
UseCacheBackendTrait::cacheGet protected function Fetches from the cache backend, respecting the use caches flag.
UseCacheBackendTrait::cacheSet protected function Stores data in the persistent cache, respecting the use caches flag.

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