77 lines
2.0 KiB
PHP
77 lines
2.0 KiB
PHP
<?php
|
|
|
|
namespace Modules\Document\Models;
|
|
|
|
use Illuminate\Database\Eloquent\Casts\Attribute;
|
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Database\Eloquent\Relations\MorphTo;
|
|
use Illuminate\Support\Facades\Storage;
|
|
use Illuminate\Support\Str;
|
|
|
|
class Document extends Model
|
|
{
|
|
use HasFactory;
|
|
|
|
protected $fillable = ['title', 'file_path', 'collection_name', 'order'];
|
|
|
|
|
|
protected static function booted()
|
|
{
|
|
static::creating(function ($model) {
|
|
$model->order = ($model::max('order') ?? 0) + 1;
|
|
});
|
|
}
|
|
|
|
public function documentable(): MorphTo
|
|
{
|
|
return $this->morphTo();
|
|
}
|
|
|
|
public function getUrl()
|
|
{
|
|
$path = $this->collection_name . '/' . $this->file_path;
|
|
return Storage::disk('public')->url($path);
|
|
}
|
|
|
|
public function getSize()
|
|
{
|
|
$path = $this->collection_name . '/' . $this->file_path;
|
|
|
|
if (Storage::disk('public')->exists($path)) {
|
|
$sizeInBytes = Storage::disk('public')->size($path);
|
|
return round($sizeInBytes / 1024, 2) . " KB";
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
|
|
public function getExtension()
|
|
{
|
|
return pathinfo($this->file_path, PATHINFO_EXTENSION);
|
|
}
|
|
|
|
public function isImageFile()
|
|
{
|
|
$imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'svg', 'webp', 'tiff', 'tif', 'ico'];
|
|
$extension = pathinfo($this->file_path, PATHINFO_EXTENSION);
|
|
return in_array(Str::lower($extension), $imageExtensions);
|
|
}
|
|
|
|
protected function documentPath(): Attribute
|
|
{
|
|
return Attribute::make(
|
|
get: function (mixed $value, array $attributes) {
|
|
$collectionName = $attributes['collection_name'];
|
|
$path = $attributes['file_path'];
|
|
return "{$collectionName}/{$path}";
|
|
}
|
|
);
|
|
}
|
|
|
|
public function scopeActive($query, int $status = 1)
|
|
{
|
|
return $query->where('status', $status);
|
|
}
|
|
}
|