refactor:优化附件管理中对上传驱动的使用

This commit is contained in:
妙码生花 2024-08-04 05:44:42 +08:00
parent f6ef7c1bd6
commit e9e0792b2a
2 changed files with 19 additions and 14 deletions

View File

@ -106,35 +106,38 @@ class Upload
/**
* 获取上传驱动句柄
* @param ?string $driver 驱动名称
* @param bool $noDriveException 找不到驱动是否抛出异常
* @return bool|Driver
*/
public function getDriver(?string $driver = null): Driver
public function getDriver(?string $driver = null, bool $noDriveException = true): bool|Driver
{
if (is_null($driver)) {
$driver = $this->driver['name'];
}
if (!isset($this->driver['handler'][$driver])) {
$class = $this->resolveDriverClass($driver);
if ($class) {
$this->driver['handler'][$driver] = new $class();
} elseif ($noDriveException) {
throw new InvalidArgumentException("Driver [$driver] not supported.");
}
return $this->driver['handler'][$driver];
}
return $this->driver['handler'][$driver] ?? false;
}
/**
* 获取驱动类
* @param string $driver
* @return string
*/
protected function resolveDriverClass(string $driver): string
protected function resolveDriverClass(string $driver): bool|string
{
if ($this->driver['namespace'] || str_contains($driver, '\\')) {
$class = str_contains($driver, '\\') ? $driver : $this->driver['namespace'] . Str::studly($driver);
if (class_exists($class)) {
return $class;
}
}
throw new InvalidArgumentException("Driver [$driver] not supported.");
return false;
}
/**

View File

@ -43,7 +43,8 @@ class Attachment extends Model
public function getFullUrlAttr($value, $row): string
{
return self::$upload->getDriver($row['storage'])->url($row['url']);
$driver = self::$upload->getDriver($row['storage'], false);
return $driver ? $driver->url($row['url']) : full_url($row['url']);
}
/**
@ -58,7 +59,8 @@ class Attachment extends Model
['storage', '=', $model->storage],
])->find();
if ($repeat) {
if (!self::$upload->getDriver($repeat->storage)->exists($repeat->url)) {
$driver = self::$upload->getDriver($repeat->storage, false);
if ($driver && !$driver->exists($repeat->url)) {
$repeat->delete();
return true;
} else {
@ -92,8 +94,8 @@ class Attachment extends Model
{
Event::trigger('AttachmentDel', $model);
$driver = self::$upload->getDriver($model->storage);
if ($driver->exists($model->url)) {
$driver = self::$upload->getDriver($model->storage, false);
if ($driver && $driver->exists($model->url)) {
$driver->delete($model->url);
}
}