Skip to content

Commit

Permalink
[Filesystem] fix cleaning up tmp files when dumpFile() fails
Browse files Browse the repository at this point in the history
  • Loading branch information
nicolas-grekas committed Nov 11, 2020
1 parent 5c547b8 commit 17b83e3
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 5 deletions.
14 changes: 9 additions & 5 deletions Filesystem.php
Original file line number Diff line number Diff line change
Expand Up @@ -686,13 +686,17 @@ public function dumpFile($filename, $content)
// when the filesystem supports chmod.
$tmpFile = $this->tempnam($dir, basename($filename));

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

@chmod($tmpFile, file_exists($filename) ? fileperms($filename) : 0666 & ~umask());
@chmod($tmpFile, file_exists($filename) ? fileperms($filename) : 0666 & ~umask());

$this->rename($tmpFile, $filename, true);
$this->rename($tmpFile, $filename, true);
} finally {
@unlink($tmpFile);
}
}

/**
Expand Down
12 changes: 12 additions & 0 deletions Tests/FilesystemTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1710,6 +1710,18 @@ public function testAppendToFileCreateTheFileIfNotExists()
$this->assertStringEqualsFile($filename, 'bar');
}

public function testDumpRemovesTmpFilesOnFailure()
{
$expected = scandir(__DIR__, \SCANDIR_SORT_ASCENDING);

try {
$this->filesystem->dumpFile(__DIR__.'/Fixtures', 'bar');
$this->fail('IOException expected.');
} catch (IOException $e) {
$this->assertSame($expected, scandir(__DIR__, \SCANDIR_SORT_ASCENDING));
}
}

public function testDumpKeepsExistingPermissionsWhenOverwritingAnExistingFile()
{
$this->markAsSkippedIfChmodIsMissing();
Expand Down

0 comments on commit 17b83e3

Please sign in to comment.