You are here

public function ProfileRoleAccessTest::testProfileOperations in Profile 8

Tests profile operations role access checks.

File

tests/src/Kernel/ProfileRoleAccessTest.php, line 156

Class

ProfileRoleAccessTest
Tests profile role access handling.

Namespace

Drupal\Tests\profile\Kernel

Code

public function testProfileOperations() {
  $user = $this
    ->createUser([], [
    "update own {$this->type1->id()} profile",
    "update own {$this->type2->id()} profile",
  ]);
  $profile1 = $this
    ->createProfile($this->type1, $user);

  // Test access to a profile type with no role requirement.
  $this
    ->assertTrue($this->accessHandler
    ->access($profile1, 'update', $user));
  $profile2 = $this
    ->createProfile($this->type2, $user);
  $this
    ->assertFalse($this->accessHandler
    ->access($profile2, 'update', $user));
  $this->accessHandler
    ->resetCache();
  $user
    ->addRole($this->role2
    ->id());
  $user
    ->save();
  $profile2 = $this
    ->reloadEntity($profile2);
  $this
    ->assertTrue($this->accessHandler
    ->access($profile2, 'update', $user));
  $operations = [
    'view',
    'update',
    'delete',
  ];
  $user2 = $this
    ->createUser([], [
    "view any {$this->type2->id()} profile",
    "update any {$this->type2->id()} profile",
    "delete any {$this->type2->id()} profile",
  ]);
  foreach ($operations as $operation) {
    $this
      ->assertTrue($this->accessHandler
      ->access($profile2, $operation, $user2));
  }
  $user
    ->removeRole($this->role2
    ->id());
  $user
    ->save();
  $this->accessHandler
    ->resetCache();
  $profile2 = $this
    ->reloadEntity($profile2);

  // Assert that each operation is denied if the profile owner doesn't have
  // one of the allowed roles.
  foreach ($operations as $operation) {
    $this
      ->assertFalse($this->accessHandler
      ->access($profile2, $operation, $user2));
  }
  $user3 = $this
    ->createUser([], [
    "view own {$this->type3->id()} profile",
    "update own {$this->type3->id()} profile",
    "delete own {$this->type3->id()} profile",
  ]);
  $profile3 = $this
    ->createProfile($this->type3, $user3);

  // Test the operations without the role affected.
  foreach ($operations as $operation) {
    $this
      ->assertFalse($this->accessHandler
      ->access($profile3, $operation, $user3));
  }
  $user3
    ->addRole($this->role1
    ->id());
  $user3
    ->save();
  $this->accessHandler
    ->resetCache();
  $profile3 = $this
    ->reloadEntity($profile3);
  foreach ($operations as $operation) {
    $this
      ->assertTrue($this->accessHandler
      ->access($profile3, $operation, $user3));
  }
}