hasActiveWorkspace example

$this->doSwitchWorkspace(NULL);
    $result = $function();
    $this->doSwitchWorkspace($previous_active_workspace);

    return $result;
  }

  /** * {@inheritdoc} */
  public function shouldAlterOperations(EntityTypeInterface $entity_type) {
    return $this->isEntityTypeSupported($entity_type) && $this->hasActiveWorkspace();
  }

  /** * {@inheritdoc} */
  public function purgeDeletedWorkspacesBatch() {
    $deleted_workspace_ids = $this->state->get('workspace.deleted', []);

    // Bail out early if there are no workspaces to purge.     if (empty($deleted_workspace_ids)) {
      return;
    }
// Switch to the 'stage' workspace and change some values for the referenced     // entities.     $this->switchToWorkspace('stage');
    $node->title->value = 'stage node 1';
    $node->save();

    // Switch back to the default workspace and run the baseline assertions.     $this->workspaceManager->switchToLive();
    $storage = $this->entityTypeManager->getStorage('node');

    $this->assertFalse($this->workspaceManager->hasActiveWorkspace());

    $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.

  public function setWorkspacesManager(WorkspaceManagerInterface $workspace_manager) {
    $this->workspaceManager = $workspace_manager;
    return $this;
  }

  /** * {@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])");

    
/** * 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. */
  


  /** * {@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));
      
// For supported entity types, signal the fact that this form is safe to use     // in a non-default workspace.     // @see \Drupal\workspaces\FormOperations::validateForm()     $form_state->set('workspace_safe', TRUE);

    // Add an entity builder to the form which marks the edited entity object as     // a pending revision. This is needed so validation constraints like     // \Drupal\path\Plugin\Validation\Constraint\PathAliasConstraintValidator     // know in advance (before hook_entity_presave()) that the new revision will     // be a pending one.     if ($this->workspaceManager->hasActiveWorkspace()) {
      $form['#entity_builders'][] = [static::class, 'entityFormEntityBuild'];
    }

    // Run the workspace conflict validation constraint when the entity form is     // being built so we can "disable" it early and display a message to the     // user, instead of allowing them to enter data that can never be saved.     foreach ($entity->validate()->getEntityViolations() as $violation) {
      if ($violation->getConstraint() instanceof EntityWorkspaceConflictConstraint) {
        $form['#markup'] = $violation->getMessage();
        $form['#access'] = FALSE;
        continue;
      }
parent::prepare();

    // 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()}'");
    }

    
/** * {@inheritdoc} */
  public function render() {
    $build = parent::render();
    if ($this->isAjax()) {
      $this->offCanvasRender($build);
    }
    else {
      // Add a row for switching to Live.       $has_active_workspace = $this->workspaceManager->hasActiveWorkspace();
      $row_live = [
        'data' => [
          'label' => [
            'data' => [
              '#markup' => $this->t('Live'),
            ],
          ],
          'owner' => '',
          'operations' => [
            'data' => [
              '#type' => 'operations',
              
$container->get('language_manager')
    );
  }

  /** * Implements a hook bridge for hook_views_query_alter(). * * @see hook_views_query_alter() */
  public function alterQuery(ViewExecutable $view, QueryPluginBase $query) {
    // Don't alter any views queries if we're not in a workspace context.     if (!$this->workspaceManager->hasActiveWorkspace()) {
      return;
    }

    // Don't alter any non-sql views queries.     if (!$query instanceof Sql) {
      return;
    }

    // Find out what entity types are represented in this query.     $entity_type_ids = [];
    foreach ($query->relationships as $info) {
      
return new static(
      $container->get('workspaces.manager'),
      $container->get('entity_type.manager')
    );
  }

  /** * {@inheritdoc} */
  public function validate($value, Constraint $constraint) {
    // The validator should run only if we are in a active workspace context.     if (!$this->workspaceManager->hasActiveWorkspace()) {
      return;
    }

    $target_entity_type_id = $value->getFieldDefinition()->getFieldStorageDefinition()->getSetting('target_type');
    $target_entity_type = $this->entityTypeManager->getDefinition($target_entity_type_id);

    if ($value->hasNewEntity() && !$this->workspaceManager->isEntityTypeSupported($target_entity_type)) {
      $this->context->addViolation($constraint->message, ['%collection_label' => $target_entity_type->getCollectionLabel()]);
    }
  }

}

  public function formAlter(array &$form, FormStateInterface $form_state$form_id) {
    // No alterations are needed if we're not in a workspace context.     if (!$this->workspaceManager->hasActiveWorkspace()) {
      return;
    }

    // Add an additional validation step for every form if we are in a     // non-default workspace.     $this->addWorkspaceValidation($form);

    // If a form has already been marked as safe or not to submit in a     // non-default workspace, we don't have anything else to do.     if ($form_state->has('workspace_safe')) {
      return;
    }

  }

  /** * @covers ::access * @dataProvider providerTestAccess */
  public function testAccess($requirements$has_active_workspace$access, array $contexts = []) {
    $route = new Route('', []$requirements);

    $workspace_manager = $this->prophesize(WorkspaceManagerInterface::class);
    $workspace_manager->hasActiveWorkspace()->willReturn($has_active_workspace);
    $access_check = new ActiveWorkspaceCheck($workspace_manager->reveal());

    $access_result = AccessResult::allowedIf($access)->addCacheContexts($contexts);
    $this->assertEquals($access_result$access_check->access($route));
  }

}
// 'workspace_2 'is empty now.     $associated_revisions = $workspace_association->getAssociatedRevisions($workspace_2->id(), 'node', [$workspace_2_node_1->id()]);
    $this->assertCount(0, $associated_revisions);
    $tracked_entities = $workspace_association->getTrackedEntities($workspace_2->id());
    $this->assertCount(0, $tracked_entities);

    $workspace_deleted = \Drupal::state()->get('workspace.deleted');
    $this->assertCount(0, $workspace_deleted);

    // Check that the deleted workspace is no longer active.     $this->assertFalse($this->workspaceManager->hasActiveWorkspace());
  }

  /** * Tests that deleting a workspace keeps its already published content. */
  public function testDeletingPublishedWorkspace() {
    $admin = $this->createUser([
      'administer nodes',
      'create workspace',
      'view own workspace',
      'edit own workspace',
      
<?php
/** * @file * Post update functions for the Workspace Update Test module. */

/** * Checks the active workspace during database updates. */
function workspace_update_test_post_update_check_active_workspace() {
  \Drupal::state()->set('workspace_update_test.has_active_workspace', \Drupal::service('workspaces.manager')->hasActiveWorkspace());
}

  public function access(Route $route) {
    if (!$route->hasRequirement('_has_active_workspace')) {
      return AccessResult::neutral();
    }

    $required_value = filter_var($route->getRequirement('_has_active_workspace'), FILTER_VALIDATE_BOOLEAN);
    return AccessResult::allowedIf($required_value === $this->workspaceManager->hasActiveWorkspace())->addCacheContexts(['workspace']);
  }

}
Home | Imprint | This part of the site doesn't use cookies.