You are here

public function MediaLibraryAccessTest::testFieldWidgetEntityFieldAccess in Drupal 8

Same name and namespace in other branches
  1. 9 core/modules/media_library/tests/src/Kernel/MediaLibraryAccessTest.php \Drupal\Tests\media_library\Kernel\MediaLibraryAccessTest::testFieldWidgetEntityFieldAccess()

Tests that the field widget opener respects entity field-level access.

File

core/modules/media_library/tests/src/Kernel/MediaLibraryAccessTest.php, line 260

Class

MediaLibraryAccessTest
Tests the media library access.

Namespace

Drupal\Tests\media_library\Kernel

Code

public function testFieldWidgetEntityFieldAccess() {
  $field_storage = FieldStorageConfig::create([
    'type' => 'entity_reference',
    'entity_type' => 'entity_test',
    // The media_library_test module will deny access to this field.
    // @see media_library_test_entity_field_access()
    'field_name' => 'field_media_no_access',
    'settings' => [
      'target_type' => 'media',
    ],
  ]);
  $field_storage
    ->save();
  FieldConfig::create([
    'field_storage' => $field_storage,
    'bundle' => 'test',
  ])
    ->save();

  /** @var \Drupal\media_library\MediaLibraryUiBuilder $ui_builder */
  $ui_builder = $this->container
    ->get('media_library.ui_builder');

  // Create an account with administrative access to the test entity type,
  // so that we can be certain that field access is checked.
  $account = $this
    ->createUser([
    'administer entity_test content',
  ]);

  // Test that access is denied even without an entity to work with.
  $state = MediaLibraryState::create('media_library.opener.field_widget', [
    'file',
    'image',
  ], 'file', 2, [
    'entity_type_id' => 'entity_test',
    'bundle' => 'test',
    'field_name' => $field_storage
      ->getName(),
  ]);
  $access_result = $ui_builder
    ->checkAccess($account, $state);
  $this
    ->assertAccess($access_result, FALSE, 'Field access denied by test module', [], [
    'url.query_args',
    'user.permissions',
  ]);

  // Assert that field access is also checked with a real entity.
  $entity = EntityTest::create([
    'type' => 'test',
    'name' => $this
      ->randomString(),
  ]);
  $entity
    ->save();
  $parameters = $state
    ->getOpenerParameters();
  $parameters['entity_id'] = $entity
    ->id();
  $state = MediaLibraryState::create($state
    ->getOpenerId(), $state
    ->getAllowedTypeIds(), $state
    ->getSelectedTypeId(), $state
    ->getAvailableSlots(), $parameters);
  $access_result = $ui_builder
    ->checkAccess($account, $state);
  $this
    ->assertAccess($access_result, FALSE, 'Field access denied by test module', [], [
    'url.query_args',
    'user.permissions',
  ]);
}