You are here

public function FileFieldPathsGeneralTest::testProgrammaticAttach in File (Field) Paths 8

Test File (Field) Paths on a programmatically added file.

File

tests/src/Functional/FileFieldPathsGeneralTest.php, line 158

Class

FileFieldPathsGeneralTest
Test general functionality.

Namespace

Drupal\Tests\filefield_paths\Functional

Code

public function testProgrammaticAttach() {

  // Create a File field with 'node/[node:nid]' as the File path and
  // '[node:nid].[file:ffp-extension-original]' as the File name.
  $field_name = mb_strtolower($this
    ->randomMachineName());
  $third_party_settings['filefield_paths']['file_path']['value'] = 'node/[node:nid]';
  $third_party_settings['filefield_paths']['file_name']['value'] = '[node:nid].[file:ffp-extension-original]';
  $this
    ->createFileField($field_name, 'node', $this->contentType, [], [], $third_party_settings);

  // Create a node without an attached file.

  /** @var \Drupal\node\Entity\Node $node */
  $node = $this
    ->drupalCreateNode([
    'type' => $this->contentType,
  ]);

  // Create a file object.

  /** @var \Drupal\file\Entity\File $test_file */
  $test_file = $this
    ->getTestFile('text');
  $test_file
    ->setPermanent();
  $test_file
    ->save();

  // Attach the file to the node.
  $node->{$field_name}
    ->setValue([
    'target_id' => $test_file
      ->id(),
  ]);
  $node
    ->save();

  // Ensure that the File path has been processed correctly.
  $node = Node::load($node
    ->id());
  $this
    ->assertSame("public://node/{$node->id()}/{$node->id()}.txt", $node->{$field_name}[0]->entity
    ->getFileUri(), 'The File path has been processed correctly.');
}