getActiveWorkspace example



  /** * {@inheritdoc} */
  protected function getBaseQuery() {
    // Don't alter any queries if we're not in a workspace context.     if (!$this->workspaceManager->hasActiveWorkspace()) {
      return parent::getBaseQuery();
    }

    $active_workspace = $this->workspaceManager->getActiveWorkspace();

    $query = $this->connection->select('path_alias', 'base_table_2');
    $wa_join = $query->leftJoin('workspace_association', NULL, "[%alias].[target_entity_type_id] = 'path_alias' AND [%alias].[target_entity_id] = [base_table_2].[id] AND [%alias].[workspace] = :active_workspace_id", [
      ':active_workspace_id' => $active_workspace->id(),
    ]);
    $query->innerJoin('path_alias_revision', 'base_table', "[%alias].[revision_id] = COALESCE([$wa_join].[target_entity_revision_id], [base_table_2].[revision_id])");

    return $query;
  }

}
'data' => [
          '#prefix' => isset($indentation) ? $this->renderer->render($indentation) : '',
          '#type' => 'link',
          '#title' => $entity->label(),
          '#url' => $entity->toUrl(),
        ],
      ],
      'owner' => $entity->getOwner()->getDisplayName(),
    ];
    $row['data'] = $row['data'] + parent::buildRow($entity);

    $active_workspace = $this->workspaceManager->getActiveWorkspace();
    if ($active_workspace && $entity->id() === $active_workspace->id()) {
      $row['class'] = ['active-workspace', 'active-workspace--not-default'];
    }
    return $row;
  }

  /** * {@inheritdoc} */
  public function getDefaultOperations(EntityInterface $entity) {
    /** @var \Drupal\workspaces\WorkspaceInterface $entity */
    
// Do not alter entity revision queries.     // @todo How about queries for the latest revision? Should we alter them to     // look for the latest workspace-specific revision?     if ($this->allRevisions) {
      return $this;
    }

    // Only alter the query if the active workspace is not the default one and     // the entity type is supported.     if ($this->workspaceManager->hasActiveWorkspace() && $this->workspaceManager->isEntityTypeSupported($this->entityType)) {
      $active_workspace = $this->workspaceManager->getActiveWorkspace();
      $this->sqlQuery->addMetaData('active_workspace_id', $active_workspace->id());
      $this->sqlQuery->addMetaData('simple_query', FALSE);

      // LEFT JOIN 'workspace_association' to the base table of the query so we       // can properly include live content along with a possible workspace       // revision.       $id_field = $this->entityType->getKey('id');
      $this->sqlQuery->leftJoin('workspace_association', 'workspace_association', "[%alias].[target_entity_type_id] = '{$this->entityTypeId}' AND [%alias].[target_entity_id] = [base_table].[$id_field] AND [%alias].[workspace] = '{$active_workspace->id()}'");
    }

    return $this;
  }
array $options = []
  ) {
    parent::__construct($connection$menu_cache_backend$cache_tags_invalidator$table$options);
  }

  /** * {@inheritdoc} */
  public function loadTreeData($menu_name, MenuTreeParameters $parameters) {
    // Add the active workspace as a menu tree condition parameter in order to     // include it in the cache ID.     if ($active_workspace = $this->workspaceManager->getActiveWorkspace()) {
      $parameters->conditions['workspace'] = $active_workspace->id();
    }
    return parent::loadTreeData($menu_name$parameters);
  }

  /** * {@inheritdoc} */
  protected function loadLinks($menu_name, MenuTreeParameters $parameters) {
    $links = parent::loadLinks($menu_name$parameters);

    
'table' => 'workspace_association',
      'field' => 'target_entity_id',
      'left_table' => $relationship,
      'left_field' => $table_data['table']['base']['field'],
      'extra' => [
        [
          'field' => 'target_entity_type_id',
          'value' => $entity_type_id,
        ],
        [
          'field' => 'workspace',
          'value' => $this->workspaceManager->getActiveWorkspace()->id(),
        ],
      ],
      'type' => 'LEFT',
    ];

    $join = $this->viewsJoinPluginManager->createInstance('standard', $definition);
    $join->adjusted = TRUE;

    return $query->queueTable('workspace_association', $relationship$join);
  }

  

  protected function bypassAccessResult(AccountInterface $account) {
    // This approach assumes that the current "global" active workspace is     // correct, i.e. if you're "in" a given workspace then you get ALL THE PERMS     // to ALL THE THINGS! That's why this is a dangerous permission.     $active_workspace = $this->workspaceManager->getActiveWorkspace();

    return AccessResult::allowedIf($active_workspace->getOwnerId() == $account->id())->cachePerUser()->addCacheableDependency($active_workspace)
      ->andIf(AccessResult::allowedIfHasPermission($account, 'bypass entity access own workspace'));
  }

}
$live_node = $storage->load($node->id());
    $this->assertEquals('live node 1', $live_node->title->value);

    $result = $storage->getQuery()
      ->accessCheck(FALSE)
      ->condition('title', 'live node 1')
      ->execute();
    $this->assertEquals([$live_node->getRevisionId() => $node->id()]$result);

    // Try the same assertions in the context of the 'stage' workspace.     $this->workspaceManager->executeInWorkspace('stage', function D) use ($node$storage) {
      $this->assertEquals('stage', $this->workspaceManager->getActiveWorkspace()->id());

      $stage_node = $storage->load($node->id());
      $this->assertEquals('stage node 1', $stage_node->title->value);

      $result = $storage->getQuery()
        ->accessCheck(FALSE)
        ->condition('title', 'stage node 1')
        ->execute();
      $this->assertEquals([$stage_node->getRevisionId() => $stage_node->id()]$result);
    });

    
/** * {@inheritdoc} */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $workspaces = $this->workspaceStorage->loadMultiple();
    $workspace_labels = [];
    foreach ($workspaces as $workspace) {
      $workspace_labels[$workspace->id()] = $workspace->label();
    }

    $active_workspace = $this->workspaceManager->getActiveWorkspace();
    if ($active_workspace) {
      unset($workspace_labels[$active_workspace->id()]);
    }

    $form['current'] = [
      '#type' => 'item',
      '#title' => $this->t('Current workspace'),
      '#markup' => $active_workspace ? $active_workspace->label() : $this->t('None'),
      '#wrapper_attributes' => [
        'class' => ['container-inline'],
      ],
    ];
/** * Sets the cache key on the alias manager cache decorator. * * KernelEvents::CONTROLLER is used in order to be executed after routing. * * @param \Symfony\Component\HttpKernel\Event\ControllerEvent $event * The Event to process. */
  public function onKernelController(ControllerEvent $event) {
    // Set the cache key on the alias manager cache decorator.     if ($event->isMainRequest() && $this->workspaceManager->hasActiveWorkspace()) {
      $cache_key = $this->workspaceManager->getActiveWorkspace()->id() . ':' . rtrim($this->currentPath->getPath($event->getRequest()), '/');
      $this->aliasManager->setCacheKey($cache_key);
    }
  }

  /** * Adds the active workspace as a cache key part to the route provider. * * @param \Symfony\Component\HttpKernel\Event\RequestEvent $event * An event object. */
  public function onKernelRequest(RequestEvent $event) {
    
$entities = [];

    // 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 $entities;
    }

    // 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.     if ($tracked_entities = $this->workspaceAssociation->getTrackedEntities($this->workspaceManager->getActiveWorkspace()->id()$entity_type_id$ids)) {
      /** @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.       foreach ($storage->loadMultipleRevisions(array_keys($tracked_entities[$entity_type_id])) as $revision) {
        $entities[$revision->id()] = $revision;
      }
    }

    return $entities;
  }

  public function checkAccess(RouteMatchInterface $route_match) {
    /** @var \Drupal\workspaces\WorkspaceInterface $workspace */
    $workspace = $route_match->getParameter('workspace');
    $active_workspace = $this->workspaceManager->getActiveWorkspace();

    $access = AccessResult::allowedIf(!$active_workspace || ($active_workspace && $active_workspace->id() != $workspace->id()))
      ->addCacheableDependency($workspace);

    return $access;
  }

}

  protected function setUp(): void {
    parent::setUp();

    $this->aliasManager = $this->prophesize(AliasManagerInterface::class)->reveal();
    $this->currentPath = $this->prophesize(CurrentPathStack::class)->reveal();
    $this->workspaceManager = $this->prophesize(WorkspaceManagerInterface::class);

    $active_workspace = $this->prophesize(WorkspaceInterface::class);
    $active_workspace->id()->willReturn('test');
    $this->workspaceManager->getActiveWorkspace()->willReturn($active_workspace->reveal());
    $this->workspaceManager->hasActiveWorkspace()->willReturn(TRUE);
  }

  /** * @covers ::onKernelRequest */
  public function testOnKernelRequestWithCacheableRouteProvider() {
    $route_provider = $this->prophesize(CacheableRouteProviderInterface::class);
    $route_provider->addExtraCacheKeyPart('workspace', 'test')->shouldBeCalled();

    // Check that WorkspaceRequestSubscriber::onKernelRequest() calls
/** * {@inheritdoc} */
  public static function postDelete(EntityStorageInterface $storage, array $entities) {
    parent::postDelete($storage$entities);

    /** @var \Drupal\workspaces\WorkspaceManagerInterface $workspace_manager */
    $workspace_manager = \Drupal::service('workspaces.manager');
    // Disable the currently active workspace if it has been deleted.     if ($workspace_manager->hasActiveWorkspace()
      && in_array($workspace_manager->getActiveWorkspace()->id()array_keys($entities), TRUE)) {
      $workspace_manager->switchToLive();
    }

    // Ensure that workspace batch purging does not happen inside a workspace.     $workspace_manager->executeOutsideWorkspace(function D) use ($workspace_manager$entities) {
      // Add the IDs of the deleted workspaces to the list of workspaces that will       // be purged on cron.       $state = \Drupal::state();
      $deleted_workspace_ids = $state->get('workspace.deleted', []);
      $deleted_workspace_ids += array_combine(array_keys($entities)array_keys($entities));
      $state->set('workspace.deleted', $deleted_workspace_ids);

      


  /** * Tests that there is no active workspace during database updates. */
  public function testActiveWorkspaceDuringUpdate() {
    /** @var \Drupal\workspaces\WorkspaceManagerInterface $workspace_manager */
    $workspace_manager = \Drupal::service('workspaces.manager');

    // Check that we have an active workspace before running the updates.     $this->assertTrue($workspace_manager->hasActiveWorkspace());
    $this->assertEquals('test', $workspace_manager->getActiveWorkspace()->id());

    $this->runUpdates();

    // Check that we didn't have an active workspace while running the updates.     // @see workspace_update_test_post_update_check_active_workspace()     $this->assertFalse(\Drupal::state()->get('workspace_update_test.has_active_workspace'));

    // Check that we have an active workspace after running the updates.     $workspace_manager = \Drupal::service('workspaces.manager');
    $this->assertTrue($workspace_manager->hasActiveWorkspace());
    $this->assertEquals('test', $workspace_manager->getActiveWorkspace()->id());
  }
/** * {@inheritdoc} */
  public static function getLabel() {
    return t('Workspace');
  }

  /** * {@inheritdoc} */
  public function getContext() {
    return $this->workspaceManager->hasActiveWorkspace() ? $this->workspaceManager->getActiveWorkspace()->id() : 'live';
  }

  /** * {@inheritdoc} */
  public function getCacheableMetadata($type = NULL) {
    // The active workspace will always be stored in the user's session.     $cacheability = new CacheableMetadata();
    $cacheability->addCacheContexts(['session']);

    return $cacheability;
  }
Home | Imprint | This part of the site doesn't use cookies.