EntityIndex.php in Multiversion 8.2
File
src/Entity/Index/EntityIndex.php
View source
<?php
namespace Drupal\multiversion\Entity\Index;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\KeyValueStore\KeyValueFactoryInterface;
use Drupal\workspaces\WorkspaceManagerInterface;
class EntityIndex implements EntityIndexInterface {
protected $collectionPrefix = 'multiversion.entity_index.id.';
protected $keyValueFactory;
protected $workspaceManager;
protected $workspaceId;
public function __construct(KeyValueFactoryInterface $key_value_factory, WorkspaceManagerInterface $workspace_manager) {
$this->keyValueFactory = $key_value_factory;
$this->workspaceManager = $workspace_manager;
}
public function useWorkspace($id) {
$this->workspaceId = $id;
return $this;
}
public function get($key) {
$values = $this
->getMultiple([
$key,
]);
return isset($values[$key]) ? $values[$key] : [];
}
public function getMultiple(array $keys) {
$workspace_id = $this
->getWorkspaceId();
$loaded_values = $this
->keyValueStore($workspace_id)
->getMultiple($keys);
if (count($keys) != count($loaded_values)) {
$loaded_values2 = $this
->keyValueStore()
->getMultiple($keys);
$loaded_values = array_merge($loaded_values, $loaded_values2);
}
return $loaded_values;
}
public function add(EntityInterface $entity) {
$this
->addMultiple([
$entity,
]);
}
public function addMultiple(array $entities) {
$workspace_id = $this
->getWorkspaceId();
$values = [];
foreach ($entities as $entity) {
$key = $this
->buildKey($entity);
$value = $this
->buildValue($entity);
if ($entity
->getEntityType()
->get('workspace') === FALSE) {
$values[0][$key] = $value;
}
else {
$values[$workspace_id][$key] = $value;
}
}
foreach ($values as $workspace_id => $value) {
$this
->keyValueStore($workspace_id)
->setMultiple($value);
}
}
protected function keyValueStore($workspace_id = 0) {
return $this->keyValueFactory
->get($this->collectionPrefix . $workspace_id);
}
protected function buildKey(EntityInterface $entity) {
return $entity
->getEntityTypeId() . ':' . $entity
->id();
}
protected function buildValue(EntityInterface $entity) {
!($is_new = $entity
->isNew());
$revision_id = $is_new ? 0 : $entity
->getRevisionId();
$status = 'indexed';
if (!$is_new && $revision_id) {
$status = $entity->_deleted->value ? 'deleted' : 'available';
}
return [
'entity_type_id' => $entity
->getEntityTypeId(),
'entity_id' => $is_new ? 0 : $entity
->id(),
'revision_id' => $revision_id,
'uuid' => $entity
->uuid(),
'rev' => $entity->_rev->value,
'is_stub' => $entity->_rev->is_stub,
'status' => $status,
];
}
protected function getWorkspaceId() {
return $this->workspaceId ?: $this->workspaceManager
->getActiveWorkspace()
->id();
}
}