You are here

public function DynamicEntityReferenceFormatterTest::testAccess in Dynamic Entity Reference 8

Same name and namespace in other branches
  1. 8.2 tests/src/Kernel/DynamicEntityReferenceFormatterTest.php \Drupal\Tests\dynamic_entity_reference\Kernel\DynamicEntityReferenceFormatterTest::testAccess()

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

File

tests/src/Kernel/DynamicEntityReferenceFormatterTest.php, line 161

Class

DynamicEntityReferenceFormatterTest
Tests the formatters functionality.

Namespace

Drupal\Tests\dynamic_entity_reference\Kernel

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 = EntityTest::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');
  $entity_type_manager = \Drupal::entityTypeManager();

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

    // Set formatter type for the 'full' view mode.
    $this
      ->getEntityDisplay($this->entityType, $this->bundle, 'default')
      ->setComponent($field_name, [
      'type' => $formatter,
      'settings' => $formatter == 'dynamic_entity_reference_entity_view' ? [
        'view_mode' => [
          $referencing_entity
            ->getEntityTypeId() => 'default',
        ],
      ] : [],
    ])
      ->save();

    // Invoke entity view.
    $entity_type_manager
      ->getViewBuilder($referencing_entity
      ->getEntityTypeId())
      ->view($referencing_entity, 'default');

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