You are here

public function TokenTest::testGetAccessTokensByEntity in Access unpublished 8

@covers \Drupal\access_unpublished\AccessTokenManager::getAccessTokensByEntity

File

tests/src/Kernel/TokenTest.php, line 81

Class

TokenTest
Test various token use cases.

Namespace

Drupal\Tests\access_unpublished\Kernel

Code

public function testGetAccessTokensByEntity() {
  $entity1 = EntityTestMulRevPub::create([
    'title' => 'Foo',
    'status' => 0,
  ]);
  $entity1
    ->save();
  $entity2 = EntityTestMulRevPub::create([
    'title' => 'Foo',
    'status' => 0,
  ]);
  $entity2
    ->save();

  // Create tokens for the entity.
  $requestTime = \Drupal::time()
    ->getRequestTime();
  $token1 = AccessToken::create([
    'entity_type' => 'entity_test_mulrevpub',
    'entity_id' => $entity1
      ->id(),
    'value' => 'iAmExpired',
    'expire' => $requestTime - 100,
  ]);
  $token1
    ->save();
  $token2 = AccessToken::create([
    'entity_type' => 'entity_test_mulrevpub',
    'entity_id' => $entity1
      ->id(),
    'value' => 'iAmValid',
    'expire' => $requestTime + 100,
  ]);
  $token2
    ->save();
  $token3 = AccessToken::create([
    'entity_type' => 'entity_test_mulrevpub',
    'entity_id' => $entity2
      ->id(),
    'value' => 'iAmExpired',
    'expire' => $requestTime - 100,
  ]);
  $token3
    ->save();
  $token4 = AccessToken::create([
    'entity_type' => 'entity_test_mulrevpub',
    'entity_id' => $entity2
      ->id(),
    'value' => 'iAmValid',
    'expire' => $requestTime + 100,
  ]);
  $token4
    ->save();

  /** @var \Drupal\access_unpublished\AccessTokenManager $manager */
  $manager = \Drupal::service('access_unpublished.access_token_manager');
  $tokens = $manager
    ->getAccessTokensByEntity($entity1);
  $uuids = array_map(function (AccessToken $token) {
    return $token
      ->uuid();
  }, $tokens);
  $this
    ->assertContains($token1
    ->uuid(), $uuids);
  $this
    ->assertContains($token2
    ->uuid(), $uuids);
  $this
    ->assertNotContains($token3
    ->uuid(), $uuids);
  $this
    ->assertNotContains($token4
    ->uuid(), $uuids);
  $tokens = $manager
    ->getAccessTokensByEntity($entity1, 'active');
  $uuids = array_map(function (AccessToken $token) {
    return $token
      ->uuid();
  }, $tokens);
  $this
    ->assertNotContains($token1
    ->uuid(), $uuids);
  $this
    ->assertContains($token2
    ->uuid(), $uuids);
  $this
    ->assertNotContains($token3
    ->uuid(), $uuids);
  $this
    ->assertNotContains($token4
    ->uuid(), $uuids);
  $tokens = $manager
    ->getAccessTokensByEntity($entity1, 'expired');
  $uuids = array_map(function (AccessToken $token) {
    return $token
      ->uuid();
  }, $tokens);
  $this
    ->assertContains($token1
    ->uuid(), $uuids);
  $this
    ->assertNotContains($token2
    ->uuid(), $uuids);
  $this
    ->assertNotContains($token3
    ->uuid(), $uuids);
  $this
    ->assertNotContains($token4
    ->uuid(), $uuids);
}