diff --git a/src/Symfony/Component/Filesystem/Filesystem.php b/src/Symfony/Component/Filesystem/Filesystem.php index 3062bdb9b7..1c65dc4b8d 100644 --- a/src/Symfony/Component/Filesystem/Filesystem.php +++ b/src/Symfony/Component/Filesystem/Filesystem.php @@ -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); } } diff --git a/src/Symfony/Component/Filesystem/Tests/FilesystemTest.php b/src/Symfony/Component/Filesystem/Tests/FilesystemTest.php index 05a5015b95..7f13b6f2e8 100644 --- a/src/Symfony/Component/Filesystem/Tests/FilesystemTest.php +++ b/src/Symfony/Component/Filesystem/Tests/FilesystemTest.php @@ -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) *