[Filesystem] Made sure Filesystem::dumpFile() overwrites an existing file.

This commit is contained in:
Jakub Zalas 2013-04-23 21:32:37 +01:00
parent 61c56fc54a
commit 4f4ec76ba4
2 changed files with 31 additions and 5 deletions

View File

@ -224,16 +224,17 @@ class Filesystem
/**
* Renames a file.
*
* @param string $origin The origin filename
* @param string $target The new filename
* @param string $origin The origin filename
* @param string $target The new filename
* @param Boolean $overwrite Whether to overwrite the target if it already exists
*
* @throws IOException When target file already exists
* @throws IOException When origin cannot be renamed
*/
public function rename($origin, $target)
public function rename($origin, $target, $overwrite = false)
{
// we check that target does not exist
if (is_readable($target)) {
if (!$overwrite && is_readable($target)) {
throw new IOException(sprintf('Cannot rename because the target "%s" already exist.', $target));
}
@ -452,7 +453,7 @@ class Filesystem
throw new IOException(sprintf('Failed to write file "%s".', $filename));
}
$this->rename($tmpFile, $filename);
$this->rename($tmpFile, $filename, true);
$this->chmod($filename, $mode);
}
}

View File

@ -639,6 +639,20 @@ class FilesystemTest extends \PHPUnit_Framework_TestCase
$this->filesystem->rename($file, $newPath);
}
public function testRenameOverwritesTheTargetIfItAlreadyExists()
{
$file = $this->workspace.DIRECTORY_SEPARATOR.'file';
$newPath = $this->workspace.DIRECTORY_SEPARATOR.'new_file';
touch($file);
touch($newPath);
$this->filesystem->rename($file, $newPath, true);
$this->assertFileNotExists($file);
$this->assertFileExists($newPath);
}
/**
* @expectedException \Symfony\Component\Filesystem\Exception\IOException
*/
@ -894,6 +908,17 @@ class FilesystemTest extends \PHPUnit_Framework_TestCase
$this->assertEquals(753, $this->getFilePermissions($filename));
}
public function testDumpFileOverwritesAnExistingFile()
{
$filename = $this->workspace.DIRECTORY_SEPARATOR.'foo.txt';
file_put_contents($filename, 'FOO BAR');
$this->filesystem->dumpFile($filename, 'bar');
$this->assertFileExists($filename);
$this->assertSame('bar', file_get_contents($filename));
}
/**
* Returns file permissions as three digits (i.e. 755)
*