75 lines
2.4 KiB
PHP
75 lines
2.4 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use App\Models\Tenant;
|
|
use Illuminate\Support\Facades\Storage;
|
|
use ZipArchive;
|
|
|
|
class CentralTenant extends Model
|
|
{
|
|
use HasFactory;
|
|
|
|
|
|
public static function listTenants()
|
|
{
|
|
return Tenant::all();
|
|
}
|
|
|
|
public static function getTenant($id)
|
|
{
|
|
return Tenant::where('id', $id)->get();
|
|
}
|
|
|
|
|
|
|
|
public static function backupTenant($tenantId) {
|
|
// 1. Identificazione del tenant
|
|
$tenant = Tenant::find($tenantId);
|
|
if (!$tenant) {
|
|
return 'Tenant non trovato.';
|
|
}
|
|
|
|
// 2. Switch al tenant
|
|
tenancy()->initialize($tenant);
|
|
|
|
// 3. Generazione del nome del file zip
|
|
$fileName = $tenantId . '_' . date('YmdHms') . '.zip';
|
|
$zipPath = storage_path('app/' . $fileName);
|
|
|
|
// 4. Creazione dell'archivio zip
|
|
$zip = new ZipArchive;
|
|
if ($zip->open($zipPath, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
|
|
return 'Impossibile creare l\'archivio zip.';
|
|
}
|
|
|
|
// 5. Dump del database
|
|
$databaseName = config('database.connections.tenant.database'); // Assumi 'tenant' come connessione per i tenant
|
|
$dumpFile = storage_path('app/temp_dump.sql');
|
|
$command = "mysqldump -u " . config('database.connections.tenant.username') . " -p" . config('database.connections.tenant.password') . " " . $databaseName . " > " . $dumpFile;
|
|
exec($command);
|
|
$zip->addFile($dumpFile, 'database.sql');
|
|
|
|
// 6. Aggiunta della cartella storage
|
|
//$storagePath = storage_path('app/tenant/' .$tenantId); // Assumi una struttura di storage separata per tenant
|
|
$storagePath = storage_path();
|
|
$files = \File::allFiles($storagePath);
|
|
foreach ($files as $file) {
|
|
$relativePath = str_replace($storagePath . '/', '', $file->getPathname());
|
|
$zip->addFile($file->getPathname(), 'storage/' . $relativePath);
|
|
}
|
|
|
|
// 7. Chiusura dell'archivio zip
|
|
$zip->close();
|
|
|
|
// 8. Download del file
|
|
// dd($zipPath);
|
|
return response()->download($zipPath, $fileName, [
|
|
'Content-Type' => 'application/zip',
|
|
'Content-Disposition' => 'attachment; filename="' . $fileName . '"',
|
|
])->deleteFileAfterSend(true); // Cancella il file dopo il download
|
|
}
|
|
}
|