You are here

public function FlagServiceTest::testGlobalFlaggingRetrieval in Flag 8.4

Tests global flags in combination with retrieval of all entity flaggings.

File

tests/src/Kernel/FlagServiceTest.php, line 217

Class

FlagServiceTest
Tests the FlagService.

Namespace

Drupal\Tests\flag\Kernel

Code

public function testGlobalFlaggingRetrieval() {

  // Create a global flag.
  $flag = Flag::create([
    'id' => strtolower($this
      ->randomMachineName()),
    'label' => $this
      ->randomString(),
    'entity_type' => 'node',
    'bundles' => [
      'article',
    ],
    'flag_type' => 'entity:node',
    'link_type' => 'reload',
    'flagTypeConfig' => [],
    'linkTypeConfig' => [],
    'global' => TRUE,
  ]);
  $flag
    ->save();

  // Flag the node.
  $flaggable_node = Node::create([
    'type' => 'article',
    'title' => $this
      ->randomMachineName(8),
  ]);
  $flaggable_node
    ->save();
  $account_1 = $this
    ->createUser();
  $account_2 = $this
    ->createUser();

  // Flag the global flag as account 1.
  $this->flagService
    ->flag($flag, $flaggable_node, $account_1);

  // Verify flagging is retrievable without an account.
  $flaggings = $this->flagService
    ->getAllEntityFlaggings($flaggable_node);
  $this
    ->assertEquals(1, count($flaggings));

  // User that flagged should see the flagging.
  $flaggings = $this->flagService
    ->getAllEntityFlaggings($flaggable_node, $account_1);
  $this
    ->assertEquals(1, count($flaggings));

  // Since this is a global flag, any user should see it returned.
  $flaggings = $this->flagService
    ->getAllEntityFlaggings($flaggable_node, $account_2);
  $this
    ->assertEquals(1, count($flaggings));

  // For a non-global flag verify only the owner gets the flag.
  $flag = Flag::create([
    'id' => strtolower($this
      ->randomMachineName()),
    'label' => $this
      ->randomString(),
    'entity_type' => 'node',
    'bundles' => [
      'article',
    ],
    'flag_type' => 'entity:node',
    'link_type' => 'reload',
    'flagTypeConfig' => [],
    'linkTypeConfig' => [],
    'global' => FALSE,
  ]);
  $flag
    ->save();
  $this->flagService
    ->flag($flag, $flaggable_node, $account_2);

  // Verify both flaggings are returned.
  $flaggings = $this->flagService
    ->getAllEntityFlaggings($flaggable_node);
  $this
    ->assertEquals(2, count($flaggings));

  // User that flagged should see both flaggings.
  $flaggings = $this->flagService
    ->getAllEntityFlaggings($flaggable_node, $account_2);
  $this
    ->assertEquals(2, count($flaggings));

  // User that hasn't used the second flag will only see the global flag.
  $flaggings = $this->flagService
    ->getAllEntityFlaggings($flaggable_node, $account_1);
  $this
    ->assertEquals(1, count($flaggings));
}