Skip to content

Commit ce78150

Browse files
author
matt
committed
Fix SftpAdapter not overwriting a file when moving
1 parent 504889d commit ce78150

File tree

2 files changed

+48
-2
lines changed

2 files changed

+48
-2
lines changed

src/AdapterTestUtilities/FilesystemAdapterTestCase.php

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -643,6 +643,37 @@ public function moving_a_file(): void
643643
});
644644
}
645645

646+
/**
647+
* @test
648+
*/
649+
public function moving_a_file_and_overwriting(): void
650+
{
651+
$this->runScenario(function() {
652+
$adapter = $this->adapter();
653+
$adapter->write(
654+
'source.txt',
655+
'contents to be moved',
656+
new Config([Config::OPTION_VISIBILITY => Visibility::PUBLIC])
657+
);
658+
$adapter->write(
659+
'destination.txt',
660+
'contents to be overwritten',
661+
new Config([Config::OPTION_VISIBILITY => Visibility::PUBLIC])
662+
);
663+
$adapter->move('source.txt', 'destination.txt', new Config());
664+
$this->assertFalse(
665+
$adapter->fileExists('source.txt'),
666+
'After moving a file should no longer exist in the original location.'
667+
);
668+
$this->assertTrue(
669+
$adapter->fileExists('destination.txt'),
670+
'After moving, a file should be present at the new location.'
671+
);
672+
$this->assertEquals(Visibility::PUBLIC, $adapter->visibility('destination.txt')->visibility());
673+
$this->assertEquals('contents to be moved', $adapter->read('destination.txt'));
674+
});
675+
}
676+
646677
/**
647678
* @test
648679
*/

src/PhpseclibV3/SftpAdapter.php

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -318,9 +318,24 @@ public function move(string $source, string $destination, Config $config): void
318318
throw UnableToMoveFile::fromLocationTo($source, $destination, $exception);
319319
}
320320

321-
if ( ! $connection->rename($sourceLocation, $destinationLocation)) {
322-
throw UnableToMoveFile::fromLocationTo($source, $destination);
321+
if ($connection->rename($sourceLocation, $destinationLocation)) {
322+
return;
323+
}
324+
325+
// Overwrite existing file / dir
326+
if ($connection->is_file($destinationLocation)) {
327+
$this->delete($destination);
328+
if ($connection->rename($sourceLocation, $destinationLocation)) {
329+
return;
330+
}
331+
} elseif ($connection->is_dir($destinationLocation)) {
332+
$this->deleteDirectory($destination);
333+
if ($connection->rename($sourceLocation, $destinationLocation)) {
334+
return;
335+
}
323336
}
337+
338+
throw UnableToMoveFile::fromLocationTo($source, $destination);
324339
}
325340

326341
public function copy(string $source, string $destination, Config $config): void

0 commit comments

Comments
 (0)