Skip to content

Commit cece029

Browse files
[Filesystem] fix cleaning up tmp files when dumpFile() fails
1 parent cdfa9c2 commit cece029

File tree

2 files changed

+24
-5
lines changed

2 files changed

+24
-5
lines changed

src/Symfony/Component/Filesystem/Filesystem.php

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -686,13 +686,17 @@ public function dumpFile($filename, $content)
686686
// when the filesystem supports chmod.
687687
$tmpFile = $this->tempnam($dir, basename($filename));
688688

689-
if (false === @file_put_contents($tmpFile, $content)) {
690-
throw new IOException(sprintf('Failed to write file "%s".', $filename), 0, null, $filename);
691-
}
689+
try {
690+
if (false === @file_put_contents($tmpFile, $content)) {
691+
throw new IOException(sprintf('Failed to write file "%s".', $filename), 0, null, $filename);
692+
}
692693

693-
@chmod($tmpFile, file_exists($filename) ? fileperms($filename) : 0666 & ~umask());
694+
@chmod($tmpFile, file_exists($filename) ? fileperms($filename) : 0666 & ~umask());
694695

695-
$this->rename($tmpFile, $filename, true);
696+
$this->rename($tmpFile, $filename, true);
697+
} finally {
698+
@unlink($tmpFile);
699+
}
696700
}
697701

698702
/**

src/Symfony/Component/Filesystem/Tests/FilesystemTest.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1710,6 +1710,21 @@ public function testAppendToFileCreateTheFileIfNotExists()
17101710
$this->assertStringEqualsFile($filename, 'bar');
17111711
}
17121712

1713+
public function testDumpRemovesTmpFilesOnFailure()
1714+
{
1715+
$expected = scandir(__DIR__, SCANDIR_SORT_ASCENDING);
1716+
$filename = $this->workspace.\DIRECTORY_SEPARATOR.'foo.txt';
1717+
file_put_contents($filename, 'FOO BAR');
1718+
chmod($filename, 0745);
1719+
1720+
try {
1721+
$this->filesystem->dumpFile(__DIR__.'/Fixtures', 'bar', null);
1722+
$this->fail('IOException expected.');
1723+
} catch (IOException $e) {
1724+
$this->assertSame($expected, scandir(__DIR__, SCANDIR_SORT_ASCENDING));
1725+
}
1726+
}
1727+
17131728
public function testDumpKeepsExistingPermissionsWhenOverwritingAnExistingFile()
17141729
{
17151730
$this->markAsSkippedIfChmodIsMissing();

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy