You are here

public function BadgeRoleTest::testUserPresave in User Badges 8

File

tests/src/Kernel/Entity/BadgeRoleTest.php, line 61

Class

BadgeRoleTest
Test role_id behavior on badges.

Namespace

Drupal\Tests\user_badges\Kernel\Entity

Code

public function testUserPresave() {

  /** @var \Drupal\user\Entity\User $user */
  $user = User::create([
    'name' => $this
      ->randomMachineName(),
  ]);
  $user
    ->save();
  $item_list = $user
    ->get('field_user_badges');
  $this
    ->assertTrue($item_list
    ->isEmpty());

  // This role has only one badge.
  $user
    ->addRole($this->rids[1]);
  $user
    ->save();
  $this
    ->assertEquals($item_list
    ->getValue(), [
    [
      'target_id' => $this->badgeIds[2],
    ],
  ]);

  // Remove the role, check no badges are left.
  $user
    ->removeRole($this->rids[1]);
  $user
    ->save();
  $this
    ->assertTrue($item_list
    ->isEmpty());

  // This role has two badges.
  $user
    ->addRole($this->rids[0]);
  $user
    ->save();
  $this
    ->assertEquals($item_list
    ->getValue(), [
    [
      'target_id' => $this->badgeIds[1],
    ],
    [
      'target_id' => $this->badgeIds[2],
    ],
  ]);

  // Now add a non-role badge.
  $item_list
    ->appendItem($this->badgeIds[0]);

  // Test for rekey: right now we have badges 1,2, 0.
  $this
    ->assertEquals($item_list
    ->count(), 3);
  for ($i = 0; $i < 3; $i++) {
    $this
      ->assertEquals($item_list
      ->get($i)
      ->getValue(), [
      'target_id' => $this->badgeIds[($i + 1) % 3],
    ]);
  }
  $user
    ->save();
  $this
    ->assertEquals($item_list
    ->count(), 3);

  // After save we have badges 0, 1, 2.
  for ($i = 0; $i < 3; $i++) {
    $this
      ->assertEquals($item_list
      ->get($i)
      ->getValue(), [
      'target_id' => $this->badgeIds[($i + 1) % 3],
    ]);
  }
}