You are here

public function EntityOperations::entityLoad in Workspace 8.2

Acts on entities when loaded.

See also

hook_entity_load()

File

src/EntityOperations.php, line 64

Class

EntityOperations
Defines a class for reacting to entity events.

Namespace

Drupal\workspace

Code

public function entityLoad(array &$entities, $entity_type_id) {

  // Only run if the entity type can belong to a workspace and we are in a
  // non-default workspace.
  if (!$this->workspaceManager
    ->shouldAlterOperations($this->entityTypeManager
    ->getDefinition($entity_type_id))) {
    return;
  }

  // Get a list of revision IDs for entities that have a revision set for the
  // current active workspace. If an entity has multiple revisions set for a
  // workspace, only the one with the highest ID is returned.
  $entity_ids = array_keys($entities);
  $max_revision_id = 'max_target_entity_revision_id';
  $results = $this->entityTypeManager
    ->getStorage('workspace_association')
    ->getAggregateQuery()
    ->accessCheck(FALSE)
    ->allRevisions()
    ->aggregate('target_entity_revision_id', 'MAX', NULL, $max_revision_id)
    ->groupBy('target_entity_id')
    ->condition('target_entity_type_id', $entity_type_id)
    ->condition('target_entity_id', $entity_ids, 'IN')
    ->condition('workspace', $this->workspaceManager
    ->getActiveWorkspace()
    ->id())
    ->execute();

  // Since hook_entity_load() is called on both regular entity load as well as
  // entity revision load, we need to prevent infinite recursion by checking
  // whether the default revisions were already swapped with the workspace
  // revision.
  // @todo This recursion protection should be removed when
  //   https://www.drupal.org/project/drupal/issues/2928888 is resolved.
  if ($results) {
    $results = array_filter($results, function ($result) use ($entities, $max_revision_id) {
      return $entities[$result['target_entity_id']]
        ->getRevisionId() != $result[$max_revision_id];
    });
  }
  if ($results) {

    /** @var \Drupal\Core\Entity\RevisionableStorageInterface $storage */
    $storage = $this->entityTypeManager
      ->getStorage($entity_type_id);

    // Swap out every entity which has a revision set for the current active
    // workspace.
    $swap_revision_ids = array_column($results, $max_revision_id);
    foreach ($storage
      ->loadMultipleRevisions($swap_revision_ids) as $revision) {
      $entities[$revision
        ->id()] = $revision;
    }
  }
}