Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 11 additions & 3 deletions src/Knp/Snappy/AbstractGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -316,6 +316,15 @@ public function getCommand($input, $output, array $options = [])
public function removeTemporaryFiles()
{
foreach ($this->temporaryFiles as $file) {
$filePath = \realpath($file);
$temporaryFolderPath = \realpath($this->getTemporaryFolder());
if (
!$filePath
|| !$temporaryFolderPath
|| !\str_starts_with($filePath, $temporaryFolderPath)
) {
continue;
}
$this->unlink($file);
}
}
Expand All @@ -328,7 +337,7 @@ public function removeTemporaryFiles()
public function getTemporaryFolder()
{
if ($this->temporaryFolder === null) {
return \sys_get_temp_dir();
$this->temporaryFolder = \sys_get_temp_dir();
}

return $this->temporaryFolder;
Expand Down Expand Up @@ -501,10 +510,9 @@ protected function createTemporaryFile($content = null, $extension = null)

if (null !== $content) {
\file_put_contents($filename, $content);
$this->temporaryFiles[] = $filename;
}

$this->temporaryFiles[] = $filename;

return $filename;
}

Expand Down
26 changes: 23 additions & 3 deletions tests/Knp/Snappy/AbstractGeneratorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -848,6 +848,26 @@ public function dataForIsAssociativeArray(): array
];
}

public function testAvoidingDeletingFileOutsideTemporaryDirectory(): void
{
$generator = $this->getMockBuilder(AbstractGenerator::class)
->setMethods([
'configure',
'unlink',
])
->setConstructorArgs(['the_binary'])
->getMock()
;

$generator
->expects($this->never())
->method('unlink')
;

$remove = new ReflectionMethod($generator, 'removeTemporaryFiles');
$remove->invoke($generator);
}

public function testCleanupEmptyTemporaryFiles(): void
{
$generator = $this->getMockBuilder(AbstractGenerator::class)
Expand All @@ -860,21 +880,21 @@ public function testCleanupEmptyTemporaryFiles(): void
;

$generator
->expects($this->once())
->expects($this->never())
->method('unlink')
;

$create = new ReflectionMethod($generator, 'createTemporaryFile');
$create->invoke($generator, null, null);

$files = new ReflectionProperty($generator, 'temporaryFiles');
$this->assertCount(1, $files->getValue($generator));
$this->assertCount(0, $files->getValue($generator));

$remove = new ReflectionMethod($generator, 'removeTemporaryFiles');
$remove->invoke($generator);
}

public function testleanupTemporaryFiles(): void
public function testCleanupTemporaryFiles(): void
{
$generator = $this->getMockBuilder(AbstractGenerator::class)
->setMethods([
Expand Down
Loading