You are here

function FileEntityEditTest::testFileEntityAssociatedUser in File Entity (fieldable files) 8.2

Check changing file associated user fields.

File

tests/src/Functional/FileEntityEditTest.php, line 78

Class

FileEntityEditTest
Create a file and test file edit functionality.

Namespace

Drupal\Tests\file_entity\Functional

Code

function testFileEntityAssociatedUser() {
  $this
    ->drupalLogin($this->admin_user);

  // Create file to edit.
  $test_file = $this
    ->getTestFile('text');
  $edit = array();
  $edit['files[upload]'] = \Drupal::service('file_system')
    ->realpath($test_file->uri);
  $this
    ->drupalPostForm('file/add', $edit, t('Next'));
  $this
    ->drupalPostForm(NULL, array(), t('Next'));

  // Check that the file was associated with the currently logged in user.
  $file = $this
    ->getFileByFilename('text-0_0.txt');
  $this
    ->assertIdentical($file
    ->getOwnerId(), $this->admin_user
    ->id(), 'File associated with admin user.');

  // Try to change the 'associated user' field to an invalid user name.
  $edit = array(
    'uid[0][target_id]' => 'invalid-name',
  );
  $this
    ->drupalPostForm('file/' . $file
    ->id() . '/edit', $edit, t('Save'));
  if (\version_compare(\Drupal::VERSION, '9.2', '<')) {
    $this
      ->assertSession()
      ->pageTextContains('There are no entities matching "invalid-name".');
  }
  else {
    $this
      ->assertSession()
      ->pageTextContains('There are no users matching "invalid-name".');
  }

  // Change the associated user field to the anonymous user (uid 0).
  $edit = array();
  $edit['uid[0][target_id]'] = 'Anonymous (0)';
  $this
    ->drupalPostForm('file/' . $file
    ->id() . '/edit', $edit, t('Save'));
  \Drupal::entityTypeManager()
    ->getStorage('file')
    ->resetCache();
  $file = File::load($file
    ->id());
  $this
    ->assertIdentical($file
    ->getOwnerId(), '0', 'File associated with anonymous user.');

  // Change the associated user field to another user's name (that is not
  // logged in).
  $edit = array();
  $edit['uid[0][target_id]'] = $this->web_user
    ->label();
  $this
    ->drupalPostForm('file/' . $file
    ->id() . '/edit', $edit, t('Save'));
  \Drupal::entityTypeManager()
    ->getStorage('file')
    ->resetCache();
  $file = File::load($file
    ->id());
  $this
    ->assertIdentical($file
    ->getOwnerId(), $this->web_user
    ->id(), 'File associated with normal user.');

  // Check that normal users cannot change the associated user information.
  $this
    ->drupalLogin($this->web_user);
  $this
    ->drupalGet('file/' . $file
    ->id() . '/edit');
  $this
    ->assertNoFieldByName('uid[0][target_id]');
}