You are here

public function EntityReferenceFormatterTest::testAccess in Drupal 8

Same name and namespace in other branches
  1. 9 core/modules/field/tests/src/Kernel/EntityReference/EntityReferenceFormatterTest.php \Drupal\Tests\field\Kernel\EntityReference\EntityReferenceFormatterTest::testAccess()
  2. 10 core/modules/field/tests/src/Kernel/EntityReference/EntityReferenceFormatterTest.php \Drupal\Tests\field\Kernel\EntityReference\EntityReferenceFormatterTest::testAccess()

Assert inaccessible items don't change the data of the fields.

File

core/modules/field/tests/src/Kernel/EntityReference/EntityReferenceFormatterTest.php, line 132

Class

EntityReferenceFormatterTest
Tests the formatters functionality.

Namespace

Drupal\Tests\field\Kernel\EntityReference

Code

public function testAccess() {

  // Revoke the 'view test entity' permission for this test.
  Role::load(RoleInterface::ANONYMOUS_ID)
    ->revokePermission('view test entity')
    ->save();
  $field_name = $this->fieldName;
  $referencing_entity = $this->container
    ->get('entity_type.manager')
    ->getStorage($this->entityType)
    ->create([
    'name' => $this
      ->randomMachineName(),
  ]);
  $referencing_entity
    ->save();
  $referencing_entity->{$field_name}->entity = $this->referencedEntity;

  // Assert user doesn't have access to the entity.
  $this
    ->assertFalse($this->referencedEntity
    ->access('view'), 'Current user does not have access to view the referenced entity.');
  $formatter_manager = $this->container
    ->get('plugin.manager.field.formatter');

  // Get all the existing formatters.
  foreach ($formatter_manager
    ->getOptions('entity_reference') as $formatter => $name) {

    // Set formatter type for the 'full' view mode.
    \Drupal::service('entity_display.repository')
      ->getViewDisplay($this->entityType, $this->bundle)
      ->setComponent($field_name, [
      'type' => $formatter,
    ])
      ->save();

    // Invoke entity view.
    \Drupal::entityTypeManager()
      ->getViewBuilder($referencing_entity
      ->getEntityTypeId())
      ->view($referencing_entity, 'default');

    // Verify the un-accessible item still exists.
    $this
      ->assertEqual($referencing_entity->{$field_name}->target_id, $this->referencedEntity
      ->id(), new FormattableMarkup('The un-accessible item still exists after @name formatter was executed.', [
      '@name' => $name,
    ]));
  }
}