function FileFieldPathTest::testUploadPath

Tests the normal formatter display on node display.

File

drupal/core/modules/file/lib/Drupal/file/Tests/FileFieldPathTest.php, line 27
Definition of Drupal\file\Tests\FileFieldPathTest.

Class

FileFieldPathTest
Tests that files are uploaded to proper locations.

Namespace

Drupal\file\Tests

Code

function testUploadPath() {
  $field_name = strtolower($this
    ->randomName());
  $type_name = 'article';
  $this
    ->createFileField($field_name, $type_name);
  $test_file = $this
    ->getTestFile('text');

  // Create a new node.
  $nid = $this
    ->uploadNodeFile($test_file, $field_name, $type_name);

  // Check that the file was uploaded to the file root.
  $node = node_load($nid, TRUE);
  $node_file = file_load($node->{$field_name}[Language::LANGCODE_NOT_SPECIFIED][0]['fid']);
  $this
    ->assertPathMatch('public://' . $test_file->filename, $node_file->uri, t('The file %file was uploaded to the correct path.', array(
    '%file' => $node_file->uri,
  )));

  // Change the path to contain multiple subdirectories.
  $this
    ->updateFileField($field_name, $type_name, array(
    'file_directory' => 'foo/bar/baz',
  ));

  // Upload a new file into the subdirectories.
  $nid = $this
    ->uploadNodeFile($test_file, $field_name, $type_name);

  // Check that the file was uploaded into the subdirectory.
  $node = node_load($nid, TRUE);
  $node_file = file_load($node->{$field_name}[Language::LANGCODE_NOT_SPECIFIED][0]['fid']);
  $this
    ->assertPathMatch('public://foo/bar/baz/' . $test_file->filename, $node_file->uri, t('The file %file was uploaded to the correct path.', array(
    '%file' => $node_file->uri,
  )));

  // Check the path when used with tokens.
  // Change the path to contain multiple token directories.
  $this
    ->updateFileField($field_name, $type_name, array(
    'file_directory' => '[current-user:uid]/[current-user:name]',
  ));

  // Upload a new file into the token subdirectories.
  $nid = $this
    ->uploadNodeFile($test_file, $field_name, $type_name);

  // Check that the file was uploaded into the subdirectory.
  $node = node_load($nid, TRUE);
  $node_file = file_load($node->{$field_name}[Language::LANGCODE_NOT_SPECIFIED][0]['fid']);

  // Do token replacement using the same user which uploaded the file, not
  // the user running the test case.
  $data = array(
    'user' => $this->admin_user,
  );
  $subdirectory = \Drupal::token()
    ->replace('[user:uid]/[user:name]', $data);
  $this
    ->assertPathMatch('public://' . $subdirectory . '/' . $test_file->filename, $node_file->uri, t('The file %file was uploaded to the correct path with token replacements.', array(
    '%file' => $node_file->uri,
  )));
}