setAccount example

$this->terms[$term->id()] = $term;

    /** @var \Drupal\taxonomy\Entity\Vocabulary $vocabulary2 */
    $vocabulary2 = $this->createVocabulary(['vid' => 'bbb']);
    $term = $this->createTerm($vocabulary2);
    $this->terms[$term->id()] = $term;

    // Create user 1 and set is as the logged in user, so that the logged in     // user has the correct permissions to view the vocabulary name.     $this->adminUser = User::create(['name' => $this->randomString()]);
    $this->adminUser->save();
    $this->container->get('current_user')->setAccount($this->adminUser);

    ViewTestData::createTestViews(static::class['taxonomy_test_views']);
  }

  /** * Tests the field handling for the Vocabulary ID. */
  public function testViewsHandlerVidField() {
    /** @var \Drupal\Core\Render\RendererInterface $renderer */
    $renderer = \Drupal::service('renderer');

    

  public function testGetAvailableContexts() {
    $context_repository = $this->container->get('context.repository');

    // Test an authenticated account.     $authenticated = User::create([
      'name' => $this->randomMachineName(),
    ]);
    $authenticated->save();
    $authenticated = User::load($authenticated->id());
    $this->container->get('current_user')->setAccount($authenticated);

    $contexts = $context_repository->getAvailableContexts();
    $this->assertArrayHasKey('@user.current_user_context:current_user', $contexts);
    $this->assertSame('entity:user', $contexts['@user.current_user_context:current_user']->getContextDefinition()->getDataType());
    $this->assertTrue($contexts['@user.current_user_context:current_user']->hasContextValue());
    $this->assertNotNull($contexts['@user.current_user_context:current_user']->getContextValue());

    // Test an anonymous account.     $anonymous = $this->prophesize(AccountInterface::class);
    $anonymous->id()->willReturn(0);
    $this->container->get('current_user')->setAccount($anonymous->reveal());

    
$user3 = User::create([
      'name' => 'user3',
      'mail' => 'user2@example.com',
    ]);
    $user3->activate();
    // Insert an inactive user who should not be seen in the block.     $inactive_time = $request_time - (60 * 60);
    $user3->setLastAccessTime($inactive_time);
    $user3->save();

    // Test block output.     \Drupal::currentUser()->setAccount($user1);

    // Test the rendering of a block.     $entity = Block::load('views_block__who_s_online_who_s_online_block');
    $output = \Drupal::entityTypeManager()
      ->getViewBuilder($entity->getEntityTypeId())
      ->view($entity, 'block');
    $this->setRawContent($this->renderer->renderRoot($output));
    $this->assertRaw('2 users', 'Correct number of online users (2 users).');
    $this->assertText($user1->getAccountName(), 'Active user 1 found in online list.');
    $this->assertText($user2->getAccountName(), 'Active user 2 found in online list.');
    $this->assertNoText($user3->getAccountName(), 'Inactive user not found in online list.');
    
$this->drupalGet(Url::fromRoute('user.login'));
    $this->submitForm([
      'name' => $account->getAccountName(),
      'pass' => $account->passRaw,
    ], 'Log in');

    // @see ::drupalUserIsLoggedIn()     $account->sessionId = $this->getSession()->getCookie(\Drupal::service('session_configuration')->getOptions(\Drupal::request())['name']);
    $this->assertTrue($this->drupalUserIsLoggedIn($account)new FormattableMarkup('User %name successfully logged in.', ['%name' => $account->getAccountName()]));

    $this->loggedInUser = $account;
    $this->container->get('current_user')->setAccount($account);
  }

  /** * Logs a user out of the Mink controlled browser and confirms. * * Confirms logout by checking the login page. */
  protected function drupalLogout() {
    // Make a request to the logout page, and redirect to the user page, the     // idea being if you were properly logged out you should be seeing a login     // screen.
/** * Tests the default owner of comment entities. */
  public function testCommentDefaultOwner() {
    $comment = Comment::create([
      'comment_type' => 'comment',
    ]);
    $this->assertEquals(0, $comment->getOwnerId());

    $user = $this->createUser();
    $this->container->get('current_user')->setAccount($user);
    $comment = Comment::create([
      'comment_type' => 'comment',
    ]);
    $this->assertEquals($user->id()$comment->getOwnerId());
  }

}


      $this->assertEquals($object->access($op$account)$result$message);
    }
  }

  /** * Ensures user labels are accessible for everyone. */
  public function testUserLabelAccess() {
    // Set up a non-admin user.     \Drupal::currentUser()->setAccount($this->createUser([], NULL, FALSE, ['uid' => 2]));

    $anonymous_user = User::getAnonymousUser();
    $user = $this->createUser();

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

    $role->grantPermission($filter_test_format->getPermissionName());
    $role->grantPermission($full_html_format->getPermissionName());
    $role->grantPermission($filtered_html_format->getPermissionName());
    $role->save();
    $this->testUser = User::create([
      'name' => 'foobar',
      'mail' => 'foobar@example.com',
    ]);
    $this->testUser->addRole($role->id());
    $this->testUser->save();
    \Drupal::service('current_user')->setAccount($this->testUser);
  }

  /** * {@inheritdoc} */
  public function getFormId() {
    return 'test_text_area_element';
  }

  /** * {@inheritdoc} */

  public function test11() {
    $account = $this->currentUser();
    return ['#markup' => $account->getAccountName()];
  }

  public function testAccount(UserInterface $user) {
    $current_user_name = $this->currentUser()->getAccountName();
    $this->currentUser()->setAccount($user);
    return ['#markup' => $current_user_name . ':' . $user->getAccountName()];
  }

  /** * Uses a subrequest to determine the content. */
  public function subrequestTest(UserInterface $user) {
    $request = \Drupal::request();
    $request = Request::create('/router_test/test13/' . $user->id(), 'GET', $request->query->all()$request->cookies->all()[]$request->server->all());

    return $this->httpKernel->handle($request, HttpKernelInterface::SUB_REQUEST);
  }

function authorize_access_allowed(Request $request) {
  $account = \Drupal::service('authentication')->authenticate($request);
  if ($account) {
    \Drupal::currentUser()->setAccount($account);
  }
  return Settings::get('allow_authorize_operations', TRUE) && \Drupal::currentUser()->hasPermission('administer software updates');
}

try {
  $request = Request::createFromGlobals();
  $kernel = DrupalKernel::createFromRequest($request$autoloader, 'prod');
  $kernel->boot();
  // A route is required for route matching.   $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('<none>'));
  $request->attributes->set(RouteObjectInterface::ROUTE_NAME, '<none>');
  
protected function setUp($import_test_views = TRUE): void {
    parent::setUp();
    $this->currentUser = $this->container->get('current_user');
    $this->setupPermissionTestData();
  }

  /** * Tests the current user filter handler with anonymous user. */
  public function testFilterCurrentUserAsAnonymous() {
    $column_map = ['uid' => 'uid'];
    $this->currentUser->setAccount(new AnonymousUserSession());

    $view = Views::getView('test_filter_current_user');
    $view->initHandlers();
    $view->filter['uid_current']->value = 0;
    $this->executeView($view);
    $expected[] = ['uid' => 1];
    $expected[] = ['uid' => 2];
    $expected[] = ['uid' => 3];
    $expected[] = ['uid' => 4];
    $this->assertIdenticalResultset($view$expected$column_map, 'Anonymous account can view all accounts when current filter is FALSE.');
    $view->destroy();

    

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

    $this->installConfig(['system']);

    // Setup the background time zones.     $this->timezones['php initial'] = date_default_timezone_get();
    $user = $this->createUser();
    $user->set('timezone', $this->timezones['user'])->save();
    // This also sets PHP's assumed time.     \Drupal::currentUser()->setAccount($user);

    // Set a reference date to use in tests.     $this->date = new DrupalDatetime('2000-01-01 12:00', NULL);

    // Create arrays listing the dates and times of $this->date formatted     // according to the various timezones of $this->timezones.     $this->dateFormat = DateFormat::load('html_date')->getPattern();
    $this->timeFormat = DateFormat::load('html_time')->getPattern();
    $date = clone $this->date;
    foreach ($this->timezones as $label => $timezone) {
      $date->setTimezone(new \DateTimeZone($timezone));
      
$this->installSchema('node', 'node_access');
  }

  /** * Tests node owner functionality. */
  public function testOwner() {
    $user = $this->createUser();

    $container = \Drupal::getContainer();
    $container->get('current_user')->setAccount($user);

    // Create a test node.     $english = Node::create([
      'type' => 'page',
      'title' => $this->randomMachineName(),
      'language' => 'en',
    ]);
    $english->save();

    $this->assertEquals($user->id()$english->getOwnerId());

    
$node->save();
    $nodes[] = $node;
    $node = Node::create([
      'title' => 'n2',
      'type' => 'default',
    ]);
    $node->save();
    $nodes[] = $node;

    $account = User::create(['name' => 'admin']);
    $account->save();
    \Drupal::currentUser()->setAccount($account);

    $connection = Database::getConnection();
    $connection->insert('history')
      ->fields([
        'uid' => $account->id(),
        'nid' => $nodes[0]->id(),
        'timestamp' => REQUEST_TIME - 100,
      ])->execute();

    $connection->insert('history')
      ->fields([
        
$expected_links .= '<li><span class="a/class">' . Html::escape('Plain "text"') . '</span></li>';
    $expected_links .= '<li><span class="unescaped">' . Html::escape('potentially unsafe text that <should> be escaped') . '</span></li>';
    $expected_links .= '<li><a href="' . Url::fromRoute('<front>')->toString() . '">' . Html::escape('Front page') . '</a></li>';
    $expected_links .= '<li><a href="' . \Drupal::urlGenerator()->generate('router_test.1') . '">' . Html::escape('Test route') . '</a></li>';
    $query = ['key' => 'value'];
    $expected_links .= '<li><a href="' . \Drupal::urlGenerator()->generate('router_test.1', $query) . '">' . Html::escape('Query test route') . '</a></li>';
    $expected_links .= '</ul>';
    $expected = $expected_heading . $expected_links;
    $this->assertThemeOutput('links', $variables$expected);

    // Verify the data- attributes for setting the "active" class on links.     \Drupal::currentUser()->setAccount(new UserSession(['uid' => 1]));
    $variables['set_active_class'] = TRUE;
    $expected_links = '';
    $expected_links .= '<ul id="somelinks">';
    $expected_links .= '<li><a href="' . Url::fromUri('base:a/link')->toString() . '">' . Html::escape('A <link>') . '</a></li>';
    $expected_links .= '<li><span class="a/class">' . Html::escape('Plain "text"') . '</span></li>';
    $expected_links .= '<li><span class="unescaped">' . Html::escape('potentially unsafe text that <should> be escaped') . '</span></li>';
    $expected_links .= '<li data-drupal-link-system-path="&lt;front&gt;"><a href="' . Url::fromRoute('<front>')->toString() . '" data-drupal-link-system-path="&lt;front&gt;">' . Html::escape('Front page') . '</a></li>';
    $expected_links .= '<li data-drupal-link-system-path="router_test/test1"><a href="' . \Drupal::urlGenerator()->generate('router_test.1') . '" data-drupal-link-system-path="router_test/test1">' . Html::escape('Test route') . '</a></li>';
    $query = ['key' => 'value'];
    $encoded_query = Html::escape(Json::encode($query));
    $expected_links .= '<li data-drupal-link-query="' . $encoded_query . '" data-drupal-link-system-path="router_test/test1"><a href="' . \Drupal::urlGenerator()->generate('router_test.1', $query) . '" data-drupal-link-query="' . $encoded_query . '" data-drupal-link-system-path="router_test/test1">' . Html::escape('Query test route') . '</a></li>';
    
return $user;
  }

  /** * Switch the current logged in user. * * @param \Drupal\Core\Session\AccountInterface $account * The user account object. */
  protected function setCurrentUser(AccountInterface $account) {
    \Drupal::currentUser()->setAccount($account);
  }

  /** * Create a user with a given set of permissions. * * @param array $permissions * Array of permission names to assign to user. Note that the user always * has the default permissions derived from the "authenticated users" role. * @param string $name * The user name. * @param bool $admin * (optional) Whether the user should be an administrator * with all the available permissions. * @param array $values * (optional) An array of initial user field values. * * @return \Drupal\user\Entity\User|false * A fully loaded user object with pass_raw property, or FALSE if account * creation fails. * * @throws \Drupal\Core\Entity\EntityStorageException * If the user creation fails. */
Home | Imprint | This part of the site doesn't use cookies.