function CopyTest::testExistingReplace

Same name in other branches
  1. 9 core/modules/file/tests/src/Kernel/CopyTest.php \Drupal\Tests\file\Kernel\CopyTest::testExistingReplace()
  2. 8.9.x core/modules/file/tests/src/Kernel/CopyTest.php \Drupal\Tests\file\Kernel\CopyTest::testExistingReplace()
  3. 11.x core/modules/file/tests/src/Kernel/CopyTest.php \Drupal\Tests\file\Kernel\CopyTest::testExistingReplace()

Tests replacement when copying over a file that already exists.

@covers ::copy

File

core/modules/file/tests/src/Kernel/CopyTest.php, line 116

Class

CopyTest
Tests the file copy function.

Namespace

Drupal\Tests\file\Kernel

Code

public function testExistingReplace() : void {
    // Setup a file to overwrite.
    $contents = $this->randomMachineName(10);
    $source = $this->createFile(NULL, $contents);
    $target = $this->createFile();
    $this->assertDifferentFile($source, $target);
    // Clone the object so we don't have to worry about the function changing
    // our reference copy.
    $result = $this->fileRepository
        ->copy(clone $source, $target->getFileUri(), FileExists::Replace);
    // Check the return status and that the contents changed.
    $this->assertNotFalse($result, 'File copied successfully.');
    $this->assertEquals($contents, file_get_contents($result->getFileUri()), 'Contents of file were overwritten.');
    $this->assertDifferentFile($source, $result);
    // Check that the correct hooks were called.
    $this->assertFileHooksCalled([
        'load',
        'copy',
        'update',
    ]);
    // Load all the affected files to check the changes that actually made it
    // to the database.
    $loaded_source = File::load($source->id());
    $loaded_target = File::load($target->id());
    $loaded_result = File::load($result->id());
    // Verify that the source file wasn't changed.
    $this->assertFileUnchanged($source, $loaded_source);
    // Verify that what was returned is what's in the database.
    $this->assertFileUnchanged($result, $loaded_result);
    // Target file was reused for the result.
    $this->assertFileUnchanged($loaded_target, $loaded_result);
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.