99 lines
2.1 KiB
PHP
99 lines
2.1 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
|
|
|
class File extends Model
|
|
{
|
|
protected $fillable = [
|
|
'file_name',
|
|
'mime_type',
|
|
'size_bytes',
|
|
'storage_uri',
|
|
'sha256',
|
|
'uploaded_by',
|
|
'uploaded_at',
|
|
];
|
|
|
|
protected $casts = [
|
|
'size_bytes' => 'integer',
|
|
'uploaded_at' => 'datetime',
|
|
];
|
|
|
|
public function user(): BelongsTo
|
|
{
|
|
return $this->belongsTo(User::class, 'uploaded_by');
|
|
}
|
|
|
|
/**
|
|
* Get the uploader name.
|
|
*/
|
|
public function getUploaderName(): string
|
|
{
|
|
return $this->user ? $this->user->name : 'Utilisateur inconnu';
|
|
}
|
|
|
|
/**
|
|
* Get the formatted file size.
|
|
*/
|
|
public function getFormattedSize(): string
|
|
{
|
|
if (!$this->size_bytes) {
|
|
return '0 B';
|
|
}
|
|
|
|
$units = ['B', 'KB', 'MB', 'GB', 'TB'];
|
|
$bytes = $this->size_bytes;
|
|
$i = 0;
|
|
|
|
while ($bytes >= 1024 && $i < count($units) - 1) {
|
|
$bytes /= 1024;
|
|
$i++;
|
|
}
|
|
|
|
return round($bytes, 2) . ' ' . $units[$i];
|
|
}
|
|
|
|
/**
|
|
* Get the file extension from the file name.
|
|
*/
|
|
public function getExtension(): string
|
|
{
|
|
return pathinfo($this->file_name, PATHINFO_EXTENSION);
|
|
}
|
|
|
|
/**
|
|
* Check if the file is an image.
|
|
*/
|
|
public function isImage(): bool
|
|
{
|
|
return str_starts_with($this->mime_type ?? '', 'image/');
|
|
}
|
|
|
|
/**
|
|
* Check if the file is a PDF.
|
|
*/
|
|
public function isPdf(): bool
|
|
{
|
|
return $this->mime_type === 'application/pdf';
|
|
}
|
|
|
|
/**
|
|
* Get the organized storage path (e.g., client/devis/filename.pdf).
|
|
*/
|
|
public function getOrganizedPath(): string
|
|
{
|
|
// Extract directory structure from storage_uri
|
|
$path = $this->storage_uri;
|
|
|
|
// Remove storage path prefix if present
|
|
if (str_contains($path, 'storage/')) {
|
|
$path = substr($path, strpos($path, 'storage/') + 8);
|
|
}
|
|
|
|
return $path;
|
|
}
|
|
}
|