You are here

public function FileFieldPathsRedirectTest::testRedirect in File (Field) Paths 8

Test File (Field) Paths Redirect functionality.

File

tests/src/Functional/FileFieldPathsRedirectTest.php, line 63

Class

FileFieldPathsRedirectTest
Test redirect module integration.

Namespace

Drupal\Tests\filefield_paths\Functional

Code

public function testRedirect() {

  // Get the public file path.
  $public_path = PublicStream::basePath();

  // Create a File field with a random File path.
  $source_dir = $this
    ->randomMachineName();
  $field_name = mb_strtolower($this
    ->randomMachineName());
  $third_party_settings['filefield_paths']['file_path']['value'] = $source_dir;
  $this
    ->createFileField($field_name, 'node', $this->contentType, [], [], $third_party_settings);

  // Create a node with a test file.

  /** @var \Drupal\file\Entity\File $test_file */
  $test_file = $this
    ->getTestFile('text');
  $nid = $this
    ->uploadNodeFile($test_file, $field_name, $this->contentType);

  // Update file path and create redirect.
  $destination_dir = $this
    ->randomMachineName();
  $edit = [
    'third_party_settings[filefield_paths][file_path][value]' => $destination_dir,
    'third_party_settings[filefield_paths][redirect]' => TRUE,
    'third_party_settings[filefield_paths][retroactive_update]' => TRUE,
  ];
  $this
    ->drupalGet("admin/structure/types/manage/{$this->contentType}/fields/node.{$this->contentType}.{$field_name}");
  $this
    ->submitForm($edit, 'Save settings');
  $this
    ->drupalGet("admin/structure/types/manage/{$this->contentType}/fields/node.{$this->contentType}.{$field_name}");

  // Check if a redirect has been created.
  $expected_redirect_source = $public_path . '/' . $source_dir . '/text-0.txt';
  $expected_redirect_destination = 'internal:/' . $public_path . '/' . $destination_dir . '/text-0.txt';
  $redirects = redirect_repository()
    ->findBySourcePath($expected_redirect_source);
  $redirect = reset($redirects);
  $this
    ->assertSame($expected_redirect_destination, $redirect
    ->getRedirect()['uri'], 'Redirect created for relocated file.');
}