perf: 优化文件重名的问题

This commit is contained in:
kuaifan 2022-06-12 20:32:34 +08:00
parent afea981a42
commit 4fd07e4c6e
2 changed files with 35 additions and 0 deletions

View File

@ -257,6 +257,7 @@ class FileController extends AbstractController
'userid' => $userid,
'created_id' => $user->userid,
]);
$file->checkName();
$file->saveBeforePids();
//
$data = File::find($file->id);
@ -307,6 +308,7 @@ class FileController extends AbstractController
'userid' => $userid,
'created_id' => $user->userid,
]);
$file->checkName();
$data = AbstractModel::transaction(function() use ($file) {
$content = FileContent::select(['content', 'text', 'size'])->whereFid($file->cid)->orderByDesc('id')->first();
$file->size = $content?->size ?: 0;
@ -383,6 +385,7 @@ class FileController extends AbstractController
}
//
$file->pid = $pid;
$file->checkName();
$file->saveBeforePids();
$files[] = $file;
}
@ -692,6 +695,7 @@ class FileController extends AbstractController
'userid' => $userid,
'created_id' => $user->userid,
]);
$dirRow->checkName();
if ($dirRow->saveBeforePids()) {
$addItem[] = File::find($dirRow->id);
}
@ -758,6 +762,7 @@ class FileController extends AbstractController
'userid' => $userid,
'created_id' => $user->userid,
]);
$file->checkName();
// 开始创建
return AbstractModel::transaction(function () use ($addItem, $webkitRelativePath, $type, $user, $data, $file) {
$file->size = $data['size'] * 1024;

View File

@ -197,6 +197,35 @@ class File extends AbstractModel
return true;
}
/**
* 检查文件名
* @param boolean $rename 重复是否自动重命名
* @return bool
*/
public function checkName($rename = true)
{
$exist = self::wherePid($this->pid)->whereUserid($this->userid)->whereName($this->name)->exists();
if (!$exist) {
return true; // 未重名
}
if (!$rename) {
return false; // 重名不需要自动重命名
}
// 自动重命名
$nextNum = 2;
if (preg_match("/(.*?)(\s+\(\d+\))*$/", $this->name)) {
$preName = preg_replace("/(.*?)(\s+\(\d+\))*$/", "$1", $this->name);
$nextNum = self::wherePid($this->pid)->whereUserid($this->userid)->where("name", "LIKE", "{$preName}%")->count() + 1;
}
$newName = "{$this->name} ({$nextNum})";
if (self::wherePid($this->pid)->whereUserid($this->userid)->whereName($newName)->exists()) {
$nextNum = rand(100, 9999);
$newName = "{$this->name} ({$nextNum})";
}
$this->name = $newName;
return true;
}
/**
* 保存前更新pids
* @return bool
@ -475,6 +504,7 @@ class File extends AbstractModel
'userid' => $newUserid,
'created_id' => 0,
]);
$file->checkName();
$file->saveBeforePids();
// 移交文件