You are here

final class EntityWarmer in Warmer 8

Same name and namespace in other branches
  1. 2.x modules/warmer_entity/src/Plugin/warmer/EntityWarmer.php \Drupal\warmer_entity\Plugin\warmer\EntityWarmer

The cache warmer for the built-in entity cache.

Plugin annotation


@Warmer(
  id = "entity",
  label = @Translation("Entity"),
  description = @Translation("Loads entities from the selected entity types & bundles to warm the entity cache.")
)

Hierarchy

Expanded class hierarchy of EntityWarmer

File

modules/warmer_entity/src/Plugin/warmer/EntityWarmer.php, line 23

Namespace

Drupal\warmer_entity\Plugin\warmer
View source
final class EntityWarmer extends WarmerPluginBase {

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  private $entityTypeManager;

  /**
   * The in-memory static entity cache.
   *
   * @var \Drupal\Core\Cache\MemoryCache\MemoryCacheInterface
   */
  private $entityMemoryCache;

  /**
   * The list of all item IDs for all entities in the system.
   *
   * Consists of <entity-type-id>:<entity-id>.
   *
   * @var array
   */
  private $iids = [];

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    $instance = parent::create($container, $configuration, $plugin_id, $plugin_definition);
    assert($instance instanceof EntityWarmer);
    $instance
      ->setEntityTypeManager($container
      ->get('entity_type.manager'));
    $instance
      ->setEntityMemoryCache($container
      ->get('entity.memory_cache'));
    return $instance;
  }

  /**
   * Injects the entity type manager.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   */
  public function setEntityTypeManager(EntityTypeManagerInterface $entity_type_manager) {
    $this->entityTypeManager = $entity_type_manager;
  }

  /**
   * Injects the entity memory cache.
   *
   * @param \Drupal\Core\Cache\MemoryCache\MemoryCacheInterface $memory_cache
   *   The memory cache.
   */
  public function setEntityMemoryCache(MemoryCacheInterface $memory_cache) {
    $this->entityMemoryCache = $memory_cache;
  }

  /**
   * {@inheritdoc}
   */
  public function loadMultiple(array $ids = []) {
    $ids_per_type = array_reduce($ids, function ($carry, $id) {
      list($entity_type_id, $entity_id) = explode(':', $id);
      if (empty($carry[$entity_type_id])) {
        $carry[$entity_type_id] = [];
      }
      $carry[$entity_type_id][] = $entity_id;
      return $carry;
    }, []);
    $output = [];
    foreach ($ids_per_type as $entity_type_id => $entity_ids) {
      try {
        $output += $this->entityTypeManager
          ->getStorage($entity_type_id)
          ->loadMultiple($entity_ids);

        // \Drupal\Core\Entity\EntityStorageBase::buildCacheId() is protected,
        // so we blindly reset the whole static cache instead of specific IDs.
        $this->entityMemoryCache
          ->deleteAll();
      } catch (PluginException $exception) {
        watchdog_exception('warmer', $exception);
      } catch (DatabaseExceptionWrapper $exception) {
        watchdog_exception('warmer', $exception);
      }
    }
    return $output;
  }

  /**
   * {@inheritdoc}
   */
  public function warmMultiple(array $items = []) {

    // The entity load already warms the entity cache. Do nothing.
    return count($items);
  }

  /**
   * {@inheritdoc}
   * TODO: This is a naive implementation.
   */
  public function buildIdsBatch($cursor) {
    $configuration = $this
      ->getConfiguration();
    if (empty($this->iids) && !empty($configuration['entity_types'])) {
      $entity_bundle_pairs = array_filter(array_values($configuration['entity_types']));
      sort($entity_bundle_pairs);
      $this->iids = array_reduce($entity_bundle_pairs, function ($iids, $entity_bundle_pair) {
        list($entity_type_id, $bundle) = explode(':', $entity_bundle_pair);
        $entity_type = $this->entityTypeManager
          ->getDefinition($entity_type_id);
        $bundle_key = $entity_type
          ->getKey('bundle');
        $id_key = $entity_type
          ->getKey('id');
        $query = $this->entityTypeManager
          ->getStorage($entity_type_id)
          ->getQuery();
        if (!empty($id_key)) {
          $query
            ->sort($id_key);
        }
        if (!empty($bundle_key)) {
          $query
            ->condition($bundle_key, $bundle);
        }
        $results = $query
          ->execute();
        $entity_ids = array_filter((array) array_values($results));
        $iids = array_merge($iids, array_map(function ($id) use ($entity_type_id) {
          return sprintf('%s:%s', $entity_type_id, $id);
        }, $entity_ids));
        return $iids;
      }, []);
    }
    $cursor_position = is_null($cursor) ? -1 : array_search($cursor, $this->iids);
    if ($cursor_position === FALSE) {
      return [];
    }
    return array_slice($this->iids, $cursor_position + 1, (int) $this
      ->getBatchSize());
  }

  /**
   * {@inheritdoc}
   */
  public function addMoreConfigurationFormElements(array $form, SubformStateInterface $form_state) {

    /** @var \Drupal\Core\Entity\EntityTypeBundleInfoInterface $bundle_info */
    $bundle_info = \Drupal::service('entity_type.bundle.info');
    $options = [];
    foreach ($this->entityTypeManager
      ->getDefinitions() as $entity_type) {
      $bundles = $bundle_info
        ->getBundleInfo($entity_type
        ->id());
      $label = (string) $entity_type
        ->getLabel();
      $entity_type_id = $entity_type
        ->id();
      $options[$label] = [];
      foreach ($bundles as $bundle_id => $bundle_data) {
        $options[$label][sprintf('%s:%s', $entity_type_id, $bundle_id)] = $bundle_data['label'];
      }
    }
    $configuration = $this
      ->getConfiguration();
    $form['entity_types'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Entity Types'),
      '#description' => $this
        ->t('Enable the entity types to warm asynchronously.'),
      '#options' => $options,
      '#default_value' => empty($configuration['entity_types']) ? [] : $configuration['entity_types'],
      '#multiple' => TRUE,
      '#attributes' => [
        'style' => 'min-height: 60em;',
      ],
    ];
    return $form;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
EntityWarmer::$entityMemoryCache private property The in-memory static entity cache.
EntityWarmer::$entityTypeManager private property The entity type manager.
EntityWarmer::$iids private property The list of all item IDs for all entities in the system.
EntityWarmer::addMoreConfigurationFormElements public function Adds additional form elements to the configuration form. Overrides WarmerInterface::addMoreConfigurationFormElements
EntityWarmer::buildIdsBatch public function TODO: This is a naive implementation. Overrides WarmerInterface::buildIdsBatch
EntityWarmer::create public static function Creates an instance of the plugin. Overrides WarmerPluginBase::create
EntityWarmer::loadMultiple public function Loads multiple items based on their IDs. Overrides WarmerInterface::loadMultiple
EntityWarmer::setEntityMemoryCache public function Injects the entity memory cache.
EntityWarmer::setEntityTypeManager public function Injects the entity type manager.
EntityWarmer::warmMultiple public function Warms multiple items. Overrides WarmerInterface::warmMultiple
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
WarmerPluginBase::$state protected property The state service.
WarmerPluginBase::$time protected property The time service.
WarmerPluginBase::buildConfigurationForm final public function Form constructor. Overrides PluginFormInterface::buildConfigurationForm
WarmerPluginBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides DependentPluginInterface::calculateDependencies
WarmerPluginBase::defaultConfiguration public function Gets default configuration for this plugin. Overrides ConfigurableInterface::defaultConfiguration 1
WarmerPluginBase::getBatchSize public function Returns the batch size for the warming operation. Overrides WarmerInterface::getBatchSize
WarmerPluginBase::getConfiguration public function Gets this plugin's configuration. Overrides ConfigurableInterface::getConfiguration
WarmerPluginBase::getFrequency public function Returns the frequency for the warming operation. Overrides WarmerInterface::getFrequency
WarmerPluginBase::isActive public function Checks if the plugin should warm in this particular moment. Overrides WarmerInterface::isActive
WarmerPluginBase::markAsEnqueued public function Marks a warmer as enqueued. Overrides WarmerInterface::markAsEnqueued
WarmerPluginBase::setConfiguration public function Sets the configuration for this plugin instance. Overrides ConfigurableInterface::setConfiguration
WarmerPluginBase::submitConfigurationForm public function Form submission handler. Overrides PluginFormInterface::submitConfigurationForm 2
WarmerPluginBase::validateConfigurationForm public function Form validation handler. Overrides PluginFormInterface::validateConfigurationForm 2
WarmerPluginBase::__construct public function Constructs a \Drupal\Component\Plugin\PluginBase object. Overrides PluginBase::__construct