3 namespace Drupal\workspaces;
5 use Drupal\Core\Cache\MemoryCache\MemoryCacheInterface;
6 use Drupal\Core\DependencyInjection\ClassResolverInterface;
7 use Drupal\Core\Entity\EntityPublishedInterface;
8 use Drupal\Core\Entity\EntityTypeInterface;
9 use Drupal\Core\Entity\EntityTypeManagerInterface;
10 use Drupal\Core\Session\AccountProxyInterface;
11 use Drupal\Core\Site\Settings;
12 use Drupal\Core\State\StateInterface;
13 use Drupal\Core\StringTranslation\StringTranslationTrait;
14 use Psr\Log\LoggerInterface;
15 use Symfony\Component\HttpFoundation\RequestStack;
18 * Provides the workspace manager.
20 class WorkspaceManager implements WorkspaceManagerInterface {
22 use StringTranslationTrait;
25 * An array of entity type IDs that can not belong to a workspace.
27 * By default, only entity types which are revisionable and publishable can
28 * belong to a workspace.
32 protected $blacklist = [
33 'workspace_association',
40 * @var \Symfony\Component\HttpFoundation\RequestStack
42 protected $requestStack;
45 * The entity type manager.
47 * @var \Drupal\Core\Entity\EntityTypeManagerInterface
49 protected $entityTypeManager;
52 * The entity memory cache service.
54 * @var \Drupal\Core\Cache\MemoryCache\MemoryCacheInterface
56 protected $entityMemoryCache;
61 * @var \Drupal\Core\Session\AccountProxyInterface
63 protected $currentUser;
68 * @var \Drupal\Core\State\StateInterface
75 * @var \Psr\Log\LoggerInterface
82 * @var \Drupal\Core\DependencyInjection\ClassResolverInterface
84 protected $classResolver;
87 * The workspace negotiator service IDs.
91 protected $negotiatorIds;
94 * The current active workspace.
96 * @var \Drupal\workspaces\WorkspaceInterface
98 protected $activeWorkspace;
101 * Constructs a new WorkspaceManager.
103 * @param \Symfony\Component\HttpFoundation\RequestStack $request_stack
105 * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
106 * The entity type manager.
107 * @param \Drupal\Core\Cache\MemoryCache\MemoryCacheInterface $entity_memory_cache
108 * The entity memory cache service.
109 * @param \Drupal\Core\Session\AccountProxyInterface $current_user
111 * @param \Drupal\Core\State\StateInterface $state
113 * @param \Psr\Log\LoggerInterface $logger
115 * @param \Drupal\Core\DependencyInjection\ClassResolverInterface $class_resolver
116 * The class resolver.
117 * @param array $negotiator_ids
118 * The workspace negotiator service IDs.
120 public function __construct(RequestStack $request_stack, EntityTypeManagerInterface $entity_type_manager, MemoryCacheInterface $entity_memory_cache, AccountProxyInterface $current_user, StateInterface $state, LoggerInterface $logger, ClassResolverInterface $class_resolver, array $negotiator_ids) {
121 $this->requestStack = $request_stack;
122 $this->entityTypeManager = $entity_type_manager;
123 $this->entityMemoryCache = $entity_memory_cache;
124 $this->currentUser = $current_user;
125 $this->state = $state;
126 $this->logger = $logger;
127 $this->classResolver = $class_resolver;
128 $this->negotiatorIds = $negotiator_ids;
134 public function isEntityTypeSupported(EntityTypeInterface $entity_type) {
135 if (!isset($this->blacklist[$entity_type->id()])
136 && $entity_type->entityClassImplements(EntityPublishedInterface::class)
137 && $entity_type->isRevisionable()) {
140 $this->blacklist[$entity_type->id()] = $entity_type->id();
147 public function getSupportedEntityTypes() {
149 foreach ($this->entityTypeManager->getDefinitions() as $entity_type_id => $entity_type) {
150 if ($this->isEntityTypeSupported($entity_type)) {
151 $entity_types[$entity_type_id] = $entity_type;
154 return $entity_types;
160 public function getActiveWorkspace() {
161 if (!isset($this->activeWorkspace)) {
162 $request = $this->requestStack->getCurrentRequest();
163 foreach ($this->negotiatorIds as $negotiator_id) {
164 $negotiator = $this->classResolver->getInstanceFromDefinition($negotiator_id);
165 if ($negotiator->applies($request)) {
166 if ($this->activeWorkspace = $negotiator->getActiveWorkspace($request)) {
173 // The default workspace negotiator always returns a valid workspace.
174 return $this->activeWorkspace;
180 public function setActiveWorkspace(WorkspaceInterface $workspace) {
181 $this->doSwitchWorkspace($workspace);
183 // Set the workspace on the proper negotiator.
184 $request = $this->requestStack->getCurrentRequest();
185 foreach ($this->negotiatorIds as $negotiator_id) {
186 $negotiator = $this->classResolver->getInstanceFromDefinition($negotiator_id);
187 if ($negotiator->applies($request)) {
188 $negotiator->setActiveWorkspace($workspace);
197 * Switches the current workspace.
199 * @param \Drupal\workspaces\WorkspaceInterface $workspace
200 * The workspace to set as active.
202 * @throws \Drupal\workspaces\WorkspaceAccessException
203 * Thrown when the current user doesn't have access to view the workspace.
205 protected function doSwitchWorkspace(WorkspaceInterface $workspace) {
206 // If the current user doesn't have access to view the workspace, they
207 // shouldn't be allowed to switch to it.
208 if (!$workspace->access('view') && !$workspace->isDefaultWorkspace()) {
209 $this->logger->error('Denied access to view workspace %workspace_label for user %uid', [
210 '%workspace_label' => $workspace->label(),
211 '%uid' => $this->currentUser->id(),
213 throw new WorkspaceAccessException('The user does not have permission to view that workspace.');
216 $this->activeWorkspace = $workspace;
218 // Clear the static entity cache for the supported entity types.
219 $cache_tags_to_invalidate = array_map(function ($entity_type_id) {
220 return 'entity.memory_cache:' . $entity_type_id;
221 }, array_keys($this->getSupportedEntityTypes()));
222 $this->entityMemoryCache->invalidateTags($cache_tags_to_invalidate);
228 public function executeInWorkspace($workspace_id, callable $function) {
229 /** @var \Drupal\workspaces\WorkspaceInterface $workspace */
230 $workspace = $this->entityTypeManager->getStorage('workspace')->load($workspace_id);
233 throw new \InvalidArgumentException('The ' . $workspace_id . ' workspace does not exist.');
236 $previous_active_workspace = $this->getActiveWorkspace();
237 $this->doSwitchWorkspace($workspace);
238 $result = $function();
239 $this->doSwitchWorkspace($previous_active_workspace);
247 public function shouldAlterOperations(EntityTypeInterface $entity_type) {
248 return $this->isEntityTypeSupported($entity_type) && !$this->getActiveWorkspace()->isDefaultWorkspace();
254 public function purgeDeletedWorkspacesBatch() {
255 $deleted_workspace_ids = $this->state->get('workspace.deleted', []);
257 // Bail out early if there are no workspaces to purge.
258 if (empty($deleted_workspace_ids)) {
262 $batch_size = Settings::get('entity_update_batch_size', 50);
264 /** @var \Drupal\workspaces\WorkspaceAssociationStorageInterface $workspace_association_storage */
265 $workspace_association_storage = $this->entityTypeManager->getStorage('workspace_association');
267 // Get the first deleted workspace from the list and delete the revisions
268 // associated with it, along with the workspace_association entries.
269 $workspace_id = reset($deleted_workspace_ids);
270 $workspace_association_ids = $this->getWorkspaceAssociationRevisionsToPurge($workspace_id, $batch_size);
272 if ($workspace_association_ids) {
273 $workspace_associations = $workspace_association_storage->loadMultipleRevisions(array_keys($workspace_association_ids));
274 foreach ($workspace_associations as $workspace_association) {
275 $associated_entity_storage = $this->entityTypeManager->getStorage($workspace_association->target_entity_type_id->value);
276 // Delete the associated entity revision.
277 if ($entity = $associated_entity_storage->loadRevision($workspace_association->target_entity_revision_id->value)) {
278 if ($entity->isDefaultRevision()) {
282 $associated_entity_storage->deleteRevision($workspace_association->target_entity_revision_id->value);
286 // Delete the workspace_association revision.
287 if ($workspace_association->isDefaultRevision()) {
288 $workspace_association->delete();
291 $workspace_association_storage->deleteRevision($workspace_association->getRevisionId());
296 // The purging operation above might have taken a long time, so we need to
297 // request a fresh list of workspace association IDs. If it is empty, we can
298 // go ahead and remove the deleted workspace ID entry from state.
299 if (!$this->getWorkspaceAssociationRevisionsToPurge($workspace_id, $batch_size)) {
300 unset($deleted_workspace_ids[$workspace_id]);
301 $this->state->set('workspace.deleted', $deleted_workspace_ids);
306 * Gets a list of workspace association IDs to purge.
308 * @param string $workspace_id
309 * The ID of the workspace.
310 * @param int $batch_size
311 * The maximum number of records that will be purged.
314 * An array of workspace association IDs, keyed by their revision IDs.
316 protected function getWorkspaceAssociationRevisionsToPurge($workspace_id, $batch_size) {
317 return $this->entityTypeManager->getStorage('workspace_association')
321 ->condition('workspace', $workspace_id)
322 ->sort('revision_id', 'ASC')
323 ->range(0, $batch_size)