Commit 2293f426 authored by Nicolas Widart's avatar Nicolas Widart Committed by GitHub

Merge pull request #403 from moebrowne/bugfix/generated-duplicate-file-names-not-always-unique

Generated Numeric File Name Suffixes Are Not Always Unique
parents 081fc584 a5c16f90
......@@ -127,14 +127,23 @@ class EloquentFileRepository extends EloquentBaseRepository implements FileRepos
private function getNewUniqueFilename($fileName)
{
$fileNameOnly = pathinfo($fileName, PATHINFO_FILENAME);
$model = $this->model->where('filename', 'LIKE', "$fileNameOnly%")->orderBy('created_at', 'desc')->first();
$extension = pathinfo($fileName, PATHINFO_EXTENSION);
$models = $this->model->where('filename', 'LIKE', "$fileNameOnly%")->get();
$versionCurrent = $models->reduce(function ($carry, $model) {
$latestFilename = pathinfo($model->filename, PATHINFO_FILENAME);
$extension = pathinfo($model->filename, PATHINFO_EXTENSION);
$version = substr($latestFilename, -1, strpos($latestFilename, '_'));
$version++;
if (preg_match('/_([0-9]+)$/', $latestFilename, $matches) !== 1) {
return $carry;
}
$version = (int)$matches[1];
return ($version > $carry) ? $version : $carry;
}, 0);
return $fileNameOnly . '_' . $version . '.' . $extension;
return $fileNameOnly . '_' . ($versionCurrent+1) . '.' . $extension;
}
/**
......
......@@ -103,10 +103,11 @@ class EloquentFileRepositoryTest extends MediaTestCase
$this->assertEquals('my-file_2.jpg', $this->file->find(3)->filename);
}
public function it_weird_edge_case()
/** @test */
public function it_can_increment_file_name_version_to_a_number_higher_than_any_existing()
{
$file = $this->file->createFromFile(\Illuminate\Http\UploadedFile::fake()->image('my-file.jpg'));
$this->file->createFromFile(\Illuminate\Http\UploadedFile::fake()->image('my-file_1.jpg'));
$this->file->createFromFile(\Illuminate\Http\UploadedFile::fake()->image('my-file.jpg'));
$this->file->destroy($file);
sleep(1);
$this->file->createFromFile(\Illuminate\Http\UploadedFile::fake()->image('my-file.jpg'));
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment