refs #2338 improve and test ImageService::getUniqueFileName()

Signed-off-by: Julien Veyssier <eneiluj@posteo.net>
This commit is contained in:
Julien Veyssier 2022-05-09 18:20:46 +02:00
Родитель 6759366d12
Коммит c0c29644b5
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4141FEE162030638
2 изменённых файлов: 48 добавлений и 4 удалений

Просмотреть файл

@ -242,13 +242,20 @@ class ImageService {
* @param string $fileName
* @return string
*/
private function getUniqueFileName(Folder $dir, string $fileName): string {
public static function getUniqueFileName(Folder $dir, string $fileName): string {
$extension = pathinfo($fileName, PATHINFO_EXTENSION);
$counter = 1;
$uniqueFileName = $fileName;
while ($dir->nodeExists($uniqueFileName)) {
$counter++;
$uniqueFileName = preg_replace('/\.' . $extension . '$/', ' (' . $counter . ').' . $extension, $fileName);
if ($extension !== '') {
while ($dir->nodeExists($uniqueFileName)) {
$counter++;
$uniqueFileName = preg_replace('/\.' . $extension . '$/', ' (' . $counter . ').' . $extension, $fileName);
}
} else {
while ($dir->nodeExists($uniqueFileName)) {
$counter++;
$uniqueFileName = preg_replace('/$/', ' (' . $counter . ')', $fileName);
}
}
return $uniqueFileName;
}

Просмотреть файл

@ -4,6 +4,7 @@ namespace OCA\Text\Tests;
use OCA\Text\AppInfo\Application;
use OCA\Text\Service\ImageService;
use OCP\Files\Folder;
class TextTest extends \PHPUnit\Framework\TestCase {
public function testDummy() {
@ -34,4 +35,40 @@ class TextTest extends \PHPUnit\Framework\TestCase {
$this->assertContains($contentName, $computedNames);
}
}
public function testGetUniqueFileName() {
$fileNameList = [
'foo.png',
'bar',
'plop.png',
'plop (2).png',
'lala.png',
'lala (2).png',
'lala (3).png',
'yay.png',
'yay (2).png',
'yay (3).png',
'yay (5).png',
'file.ext.ext',
];
$folder = $this->createMock(Folder::class);
$folder->expects(self::any())
->method('nodeExists')
->willReturnCallback(function ($name) use ($fileNameList) {
return in_array($name, $fileNameList);
});
// files that do not exist yet
$this->assertEquals('doesNotExistYet', ImageService::getUniqueFileName($folder, 'doesNotExistYet'));
$this->assertEquals('doesNotExistYet.png', ImageService::getUniqueFileName($folder, 'doesNotExistYet.png'));
// files that already exist
$this->assertEquals('foo (2).png', ImageService::getUniqueFileName($folder, 'foo.png'));
$this->assertEquals('bar (2)', ImageService::getUniqueFileName($folder, 'bar'));
$this->assertEquals('plop (3).png', ImageService::getUniqueFileName($folder, 'plop.png'));
$this->assertEquals('lala (4).png', ImageService::getUniqueFileName($folder, 'lala.png'));
$this->assertEquals('yay (4).png', ImageService::getUniqueFileName($folder, 'yay.png'));
$this->assertEquals('file.ext (2).ext', ImageService::getUniqueFileName($folder, 'file.ext.ext'));
}
}