52 lines
1.4 KiB
PHP
52 lines
1.4 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Services;
|
|
|
|
use Exception;
|
|
|
|
final class FileStorageService
|
|
{
|
|
private string $storagePath;
|
|
|
|
public function __construct()
|
|
{
|
|
$this->storagePath = $_ENV['STORAGE_PATH'] ?? dirname(__DIR__, 2) . '/storage';
|
|
}
|
|
|
|
public function store(array $file, string $tenantId, string $companyId): string
|
|
{
|
|
// 1. Validate MIME
|
|
$finfo = finfo_open(FILEINFO_MIME_TYPE);
|
|
$mime = finfo_file($finfo, $file['tmp_name']);
|
|
finfo_close($finfo);
|
|
|
|
$allowedMimes = ['application/pdf', 'image/jpeg', 'image/png', 'image/webp'];
|
|
if (!in_array($mime, $allowedMimes)) {
|
|
throw new Exception("نوع الملف غير مسموح به");
|
|
}
|
|
|
|
// 2. Generate path
|
|
$dir = "{$this->storagePath}/invoices/{$tenantId}/{$companyId}";
|
|
if (!is_dir($dir)) {
|
|
mkdir($dir, 0775, true);
|
|
}
|
|
|
|
$extension = pathinfo($file['name'], PATHINFO_EXTENSION);
|
|
$filename = hash('sha256', $file['name'] . time() . uniqid()) . '.' . $extension;
|
|
$targetPath = "{$dir}/{$filename}";
|
|
|
|
if (!move_uploaded_file($file['tmp_name'], $targetPath)) {
|
|
throw new Exception("فشل رفع الملف");
|
|
}
|
|
|
|
return $targetPath;
|
|
}
|
|
|
|
public function getHash(string $filePath): string
|
|
{
|
|
return hash_file('sha256', $filePath);
|
|
}
|
|
}
|