'integer', 'height' => 'integer', 'size' => 'float', 'is_unhealthy' => 'bool', ]; protected static function booted() { static::creating(function (self $image) { $image->key = $image->generateKey(); }); static::deleting(function (self $image) { // TODO 检测是否启用了队列,放置队列中异步删除 // 在当前图片所属的策略中是否存在其他相同 md5 和 sha1 的记录,没有则可以删除物理文件 if (!static::query() ->where('strategy_id', $image->strategy_id) ->where('id', '<>', $image->id) ->where('md5', $image->md5) ->where('sha1', $image->sha1) ->exists() ) { $image->filesystem()->delete($image->pathname); } }); } public function filename(): Attribute { return new Attribute(fn() => $this->alias_name ?: $this->origin_name); } public function pathname(): Attribute { return new Attribute(fn() => "{$this->path}/{$this->name}"); } public function url(): Attribute { return new Attribute(function () { if (!$this->strategy) { return Storage::disk('uploads')->url($this->pathname); } // 是否启用了获取图片直链功能 if ($this->strategy->configs->get(LocalOption::IsEnableOriginUrl)) { return rtrim($this->strategy->configs->get(LocalOption::Domain), '/').'/'.$this->pathname; } else { // 原图保护 return asset("{$this->key}.{$this->extension}"); } }); } public function links(): Attribute { return new Attribute(fn() => collect([ 'url' => $this->url, 'html' => "<img src=\"{$this->url}\" alt=\"{$this->origin_name}\" title=\"{$this->origin_name}\" />", 'bbcode' => "[img]{$this->url}[/img]", 'markdown' => "![{$this->origin_name}]({$this->url})", 'markdown_with_link' => "[![{$this->origin_name}]({$this->url})]({$this->url})", ])); } public function filesystem(): Filesystem { return new Filesystem((new ImageService())->getAdapter($this->strategy->key, $this->strategy->configs)); } public function user(): BelongsTo { return $this->belongsTo(User::class, 'user_id', 'id'); } public function album(): BelongsTo { return $this->belongsTo(Album::class, 'album_id', 'id'); } public function strategy(): BelongsTo { return $this->belongsTo(Strategy::class, 'strategy_id', 'id'); } private function generateKey($length = 6): string { $key = Str::random($length); if (self::query()->where('key', $key)->exists()) { return $this->generateKey(++$length); } return $key; } }