Skip to content

Commit

Permalink
Use of Winter's Str::unique() and File::unique() helpers
Browse files Browse the repository at this point in the history
  • Loading branch information
damsfx committed Aug 1, 2024
1 parent 16955e0 commit ce76872
Showing 1 changed file with 19 additions and 11 deletions.
30 changes: 19 additions & 11 deletions modules/system/classes/MediaLibrary.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@
use ApplicationException;
use Cache;
use Config;
use File;
use Illuminate\Filesystem\FilesystemAdapter;
use Lang;
use Storage;
use SystemException;
use Url;
use Winter\Storm\Filesystem\Definitions as FileDefinitions;
use Winter\Storm\Support\Arr;
use Winter\Storm\Support\Str;
use Winter\Storm\Support\Svg;

Expand Down Expand Up @@ -907,15 +909,18 @@ protected function generateRandomTmpFolderName($location)
public function generateIncrementedFileName($path): string
{
$pathInfos = pathinfo($path);
$sameFiles = array_filter(
$this->getStorageDisk()->files(dirname($this->getMediaPath($path))),
$dirName = dirname($this->getMediaPath($path));

$sameFilesInFolder = Arr::map(array_filter(
$this->getStorageDisk()->files($dirName),
function ($file) use ($pathInfos) {
return preg_match('/'. $pathInfos['filename'] .'-(\d*)\.'. $pathInfos['extension'] .'$/U', $file);
return preg_match('/'. $pathInfos['filename'] .'(_(\d*))?\.'. $pathInfos['extension'] .'$/U', $file);
}
);
$newIndex = count($sameFiles) + 1;
), function ($value) use ($dirName) {
return str_replace($dirName .'/', '', '/'. $value);
});

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

/**
Expand All @@ -927,14 +932,17 @@ function ($file) use ($pathInfos) {
*/
public function generateIncrementedFolderName($path)
{
$sameFolders = array_filter(
$dirName = dirname($this->getMediaPath($path));

$sameFolders = Arr::map(array_filter(
$this->getStorageDisk()->directories(dirname($this->getMediaPath($path))),
function ($folder) use ($path) {
return preg_match('/'. basename($path) .'-(\d*)$/U', $folder);
return preg_match('/'. basename($path) .'(_(\d*))?$/U', $folder);
}
);
$newIndex = count($sameFolders) + 1;
), function ($value) use ($dirName) {
return str_replace($dirName .'/', '', '/'. $value);
});

return basename($path) .'-' . $newIndex;
return Str::unique(basename($path), $sameFolders);
}
}

0 comments on commit ce76872

Please sign in to comment.