switchTo example


  protected function doTestFilters($display_id) {
    $comment = $this->comments[0];
    $comment_anonymous = $this->comments[1];
    /** @var \Drupal\Core\Session\AccountSwitcherInterface $account_switcher */
    $account_switcher = \Drupal::service('account_switcher');

    /** @var \Drupal\Core\Render\RendererInterface $renderer */
    $renderer = \Drupal::service('renderer');

    $account_switcher->switchTo($this->adminUser);
    $executable = Views::getView('comment');
    $build = $executable->preview($display_id);
    $this->setRawContent($renderer->renderRoot($build));

    // Assert the exposed filters on the admin page.     $this->assertField('subject');
    $this->assertField('author_name');
    $this->assertField('langcode');

    $elements = $this->cssSelect('input[type="checkbox"]');
    $this->assertCount(2, $elements, 'There are two comments on the page.');
    

      ],
    ]);
    $view->save();

    /** @var \Drupal\Core\Session\AccountSwitcherInterface $account_switcher */
    $account_switcher = \Drupal::service('account_switcher');

    /** @var \Drupal\Core\Render\RendererInterface $renderer */
    $renderer = \Drupal::service('renderer');

    $account_switcher->switchTo($this->adminUser);
    $executable = Views::getView($view_id);
    $build = $executable->preview();
    $this->setRawContent($renderer->renderRoot($build));

    $this->assertLink('My comment title');
    $this->assertLink('Anonymous comment title');
    // Display plugin of the view is showing the name field. When comment     // belongs to an authenticated user the name field has no value.     $comment_author = $this->xpath('//div[contains(@class, :class)]/span[normalize-space(text())=""]', [
      ':class' => 'views-field-subject',
    ]);
    
$referencing_entity = EntityTest::create([
      'field_test' => [
        ['entity' => $published_node],
        ['entity' => $unpublished_node],
        ['entity' => $different_bundle_node],
        ['entity' => $deleted_node],
      ],
    ]);

    // Check that users with access are able pass the validation for fields     // without pre-existing content.     $this->container->get('account_switcher')->switchTo($user_with_access);

    $violations = $referencing_entity->field_test->validate();
    $this->assertCount(0, $violations);

    // Check that users without access are not able pass the validation for     // fields without pre-existing content.     $this->container->get('account_switcher')->switchTo($user_without_access);

    $violations = $referencing_entity->field_test->validate();
    $this->assertCount(1, $violations);
    $this->assertEquals(t('This entity (%type: %id) cannot be referenced.', [
      
// The current user is allowed to view user labels.     $this->assertEntityAccess([
      'create' => FALSE,
      'update' => FALSE,
      'delete' => FALSE,
      'view' => FALSE,
      'view label' => TRUE,
    ]$user);

    // Switch to an anonymous user account.     $account_switcher = \Drupal::service('account_switcher');
    $account_switcher->switchTo(new AnonymousUserSession());

    // The anonymous user is allowed to view the anonymous user label.     $this->assertEntityAccess([
      'create' => FALSE,
      'update' => FALSE,
      'delete' => FALSE,
      'view' => FALSE,
      'view label' => TRUE,
    ]$anonymous_user);

    // The anonymous user is allowed to view user labels.

  public function testPluginArgumentDefaultCurrentUser() {
    $this->installSchema('system', ['sequences']);
    $this->installEntitySchema('user');
    ViewTestData::createTestViews(static::class['user_test_views']);

    // Create a user to test.     $account = $this->createUser();

    // Switch the user.     $this->container->get('account_switcher')->switchTo($account);

    $view = Views::getView('test_plugin_argument_default_current_user');
    $view->initHandlers();

    $this->assertEquals($account->id()$view->argument['null']->getDefaultArgument(), 'Uid of the current user is used.');
  }

}


  /** * {@inheritdoc} */
  public function run() {
    // Allow execution to continue even if the request gets cancelled.     @ignore_user_abort(TRUE);

    // Force the current user to anonymous to ensure consistent permissions on     // cron runs.     $this->accountSwitcher->switchTo(new AnonymousUserSession());

    // Try to allocate enough time to run all the hook_cron implementations.     Environment::setTimeLimit(240);

    $return = FALSE;

    // Try to acquire cron lock.     if (!$this->lock->acquire('cron', 900.0)) {
      // Cron is still running normally.       $this->logger->warning('Attempting to re-run cron while it is already running.');
    }
    

  public function validateEntity(FieldableEntityInterface $entity) {
    // Entity validation can require the user that owns the entity. Switch to     // use that user during validation.     // As an example:     // @see \Drupal\Core\Entity\Plugin\Validation\Constraint\ValidReferenceConstraint     $account = $entity instanceof EntityOwnerInterface ? $entity->getOwner() : NULL;
    // Validate account exists as the owner reference could be invalid for any     // number of reasons.     if ($account) {
      $this->accountSwitcher->switchTo($account);
    }
    // This finally block ensures that the account is always switched back, even     // if an exception was thrown. Any validation exceptions are intentionally     // left unhandled. They should be caught and logged by a catch block     // surrounding the row import and then added to the migration messages table     // for the current row.     try {
      $violations = $entity->validate();
    } finally {
      if ($account) {
        $this->accountSwitcher->switchBack();
      }

      ],
    ]);
    $entity->save();

    /** @var \Drupal\Core\Session\AccountSwitcherInterface $account_switcher */
    $account_switcher = \Drupal::service('account_switcher');

    /** @var \Drupal\Core\Render\RendererInterface $renderer */
    $renderer = \Drupal::service('renderer');

    $account_switcher->switchTo($this->userWithAccess);
    $executable = Views::getView($view_id);
    $build = $executable->preview();
    $this->setRawContent($renderer->renderRoot($build));

    $this->assertText($field_content);
    $this->assertTrue(isset($executable->field[$field_name]));

    $account_switcher->switchTo($this->userWithoutAccess);
    $executable = Views::getView($view_id);
    $build = $executable->preview();
    $this->setRawContent($renderer->renderRoot($build));

    
$this->assertEquals(1, $user1->id());

    $authenticated_user = $this->createUser(['administer permissions']);
    $role = $authenticated_user->getRoles()[1];

    $test_element = [
      '#cache' => [
        'keys' => ['test'],
        'contexts' => ['user', 'user.permissions'],
      ],
    ];
    \Drupal::service('account_switcher')->switchTo($authenticated_user);
    $element = $test_element;
    $element['#markup'] = 'content for authenticated users';
    $output = \Drupal::service('renderer')->renderRoot($element);
    $this->assertEquals('content for authenticated users', $output);

    // Verify that the render caching is working so that other tests can be     // trusted.     $element = $test_element;
    $element['#markup'] = 'this should not be visible';
    $output = \Drupal::service('renderer')->renderRoot($element);
    $this->assertEquals('content for authenticated users', $output);

    
$view = Views::getView('test_access_perm');
    $display = &$view->storage->getDisplay('default');
    $display['display_options']['cache'] = [
      'type' => 'tag',
    ];

    $renderer = $this->container->get('renderer');
    $account_switcher = $this->container->get('account_switcher');

    // First access as user without access.     $build = DisplayPluginBase::buildBasicRenderable('test_access_perm', 'default');
    $account_switcher->switchTo($this->webUser);
    $this->assertEmpty($renderer->renderPlain($build));

    // Then with access.     $build = DisplayPluginBase::buildBasicRenderable('test_access_perm', 'default');
    $account_switcher->switchTo($this->normalUser);
    $this->assertNotEmpty($renderer->renderPlain($build));
  }

}

  public function testCliPublishing() {
    $this->initializeWorkspacesModule();
    $this->switchToWorkspace('stage');

    // Add a workspace-specific revision to a pre-existing node.     $node = $this->entityTypeManager->getStorage('node')->load(2);
    $node->title->value = 'stage - 2 - r3 - published';
    $node->save();

    // Switch to an anonymous user account and the 'Live' workspace.     \Drupal::service('account_switcher')->switchTo(new AnonymousUserSession());
    \Drupal::service('workspaces.manager')->switchToLive();

    // Publish the workspace as anonymous, simulating a CLI request.     $this->workspaces['stage']->publish();
  }

  /** * Tests entity query overrides without any conditions. */
  public function testEntityQueryWithoutConditions() {
    $this->initializeWorkspacesModule();
    
$this->normalRole => $this->normalRole,
    ];
    $view->save();

    /** @var \Drupal\Core\Render\RendererInterface $renderer */
    $renderer = \Drupal::service('renderer');
    /** @var \Drupal\Core\Session\AccountSwitcherInterface $account_switcher */
    $account_switcher = \Drupal::service('account_switcher');

    // First access as user with access.     $build = DisplayPluginBase::buildBasicRenderable('test_access_role', 'default');
    $account_switcher->switchTo($this->normalUser);
    $result = $renderer->renderPlain($build);
    $this->assertContains('user.roles', $build['#cache']['contexts']);
    $this->assertEquals(['config:views.view.test_access_role']$build['#cache']['tags']);
    $this->assertEquals(Cache::PERMANENT, $build['#cache']['max-age']);
    $this->assertNotSame('', $result);

    // Then without access.     $build = DisplayPluginBase::buildBasicRenderable('test_access_role', 'default');
    $account_switcher->switchTo($this->webUser);
    $result = $renderer->renderPlain($build);
    // @todo Fix this in https://www.drupal.org/node/2551037,

class AccountSwitcherTest extends KernelTestBase {

  public function testAccountSwitching() {
    $session_handler = $this->container->get('session_handler.write_safe');
    $user = $this->container->get('current_user');
    $switcher = $this->container->get('account_switcher');
    $original_user = $user->getAccount();
    $original_session_saving = $session_handler->isSessionWritable();

    // Switch to user with uid 2.     $switcher->switchTo(new UserSession(['uid' => 2]));

    // Verify that the active user has changed, and that session saving is     // disabled.     $this->assertEquals(2, $user->id(), 'Switched to user 2.');
    $this->assertFalse($session_handler->isSessionWritable(), 'Session saving is disabled.');

    // Perform a second (nested) user account switch.     $switcher->switchTo(new UserSession(['uid' => 3]));
    $this->assertEquals(3, $user->id(), 'Switched to user 3.');

    // Revert to the user session that was active between the first and second
'created' => REQUEST_TIME,
    ]);

    // Now create a user with the ability to edit bar but not foo.     $this->testUser = $this->createUser([
      'access content overview',
      'access content',
      'edit any bar content',
      'delete any bar content',
    ]);
    // And switch to that user.     $this->container->get('account_switcher')->switchTo($this->testUser);
  }

  /** * Tests that dropbutton markup doesn't leak between rows. */
  public function testDropbuttonMarkupShouldNotLeakBetweenRows() {
    $view = Views::getView('test_dropbutton');
    $view->setDisplay();
    $view->preExecute([]);
    $view->execute();

    
$this->assertNull(\Drupal::formBuilder()->getCache($wrong_form_build_id$cached_form_state), 'No form returned from cache');
    $cached_form_state_example = $cached_form_state->get('example');
    $this->assertEmpty($cached_form_state_example, 'Cached form state was not loaded');
  }

  /** * Tests the form cache without a logged-in user. */
  public function testNoCacheToken() {
    // Switch to an anonymous user account.     $account_switcher = \Drupal::service('account_switcher');
    $account_switcher->switchTo(new AnonymousUserSession());

    $this->formState->set('example', $this->randomMachineName());
    \Drupal::formBuilder()->setCache($this->formBuildId, $this->form, $this->formState);

    $cached_form_state = new FormState();
    $cached_form = \Drupal::formBuilder()->getCache($this->formBuildId, $cached_form_state);
    $this->assertEquals($this->form['#property']$cached_form['#property']);
    $this->assertArrayNotHasKey('#cache_token', $cached_form, 'Form has no cache token');
    $this->assertEquals($this->formState->get('example')$cached_form_state->get('example'));

    // Restore user account.
Home | Imprint | This part of the site doesn't use cookies.