Skip to content

Commit ce76872

Browse files
committed
Use of Winter's Str::unique() and File::unique() helpers
- need wintercms/storm#186
1 parent 16955e0 commit ce76872

1 file changed

Lines changed: 19 additions & 11 deletions

File tree

modules/system/classes/MediaLibrary.php

Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,14 @@
55
use ApplicationException;
66
use Cache;
77
use Config;
8+
use File;
89
use Illuminate\Filesystem\FilesystemAdapter;
910
use Lang;
1011
use Storage;
1112
use SystemException;
1213
use Url;
1314
use Winter\Storm\Filesystem\Definitions as FileDefinitions;
15+
use Winter\Storm\Support\Arr;
1416
use Winter\Storm\Support\Str;
1517
use Winter\Storm\Support\Svg;
1618

@@ -907,15 +909,18 @@ protected function generateRandomTmpFolderName($location)
907909
public function generateIncrementedFileName($path): string
908910
{
909911
$pathInfos = pathinfo($path);
910-
$sameFiles = array_filter(
911-
$this->getStorageDisk()->files(dirname($this->getMediaPath($path))),
912+
$dirName = dirname($this->getMediaPath($path));
913+
914+
$sameFilesInFolder = Arr::map(array_filter(
915+
$this->getStorageDisk()->files($dirName),
912916
function ($file) use ($pathInfos) {
913-
return preg_match('/'. $pathInfos['filename'] .'-(\d*)\.'. $pathInfos['extension'] .'$/U', $file);
917+
return preg_match('/'. $pathInfos['filename'] .'(_(\d*))?\.'. $pathInfos['extension'] .'$/U', $file);
914918
}
915-
);
916-
$newIndex = count($sameFiles) + 1;
919+
), function ($value) use ($dirName) {
920+
return str_replace($dirName .'/', '', '/'. $value);
921+
});
917922

918-
return $pathInfos['filename'] .'-' . $newIndex . '.' . $pathInfos['extension'];
923+
return File::unique($pathInfos['basename'], $sameFilesInFolder);
919924
}
920925

921926
/**
@@ -927,14 +932,17 @@ function ($file) use ($pathInfos) {
927932
*/
928933
public function generateIncrementedFolderName($path)
929934
{
930-
$sameFolders = array_filter(
935+
$dirName = dirname($this->getMediaPath($path));
936+
937+
$sameFolders = Arr::map(array_filter(
931938
$this->getStorageDisk()->directories(dirname($this->getMediaPath($path))),
932939
function ($folder) use ($path) {
933-
return preg_match('/'. basename($path) .'-(\d*)$/U', $folder);
940+
return preg_match('/'. basename($path) .'(_(\d*))?$/U', $folder);
934941
}
935-
);
936-
$newIndex = count($sameFolders) + 1;
942+
), function ($value) use ($dirName) {
943+
return str_replace($dirName .'/', '', '/'. $value);
944+
});
937945

938-
return basename($path) .'-' . $newIndex;
946+
return Str::unique(basename($path), $sameFolders);
939947
}
940948
}

0 commit comments

Comments
 (0)