81 lines
2.9 KiB
PHP
Executable File
81 lines
2.9 KiB
PHP
Executable File
<?php
|
|
namespace App\Services\Admin;
|
|
|
|
use App\Models\Amministratore;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Support\Facades\Log;
|
|
use Illuminate\Support\Facades\Schema;
|
|
|
|
class AdministratorProvisioningService
|
|
{
|
|
public function provision(Amministratore $amministratore, bool $createDatabase = true, bool $force = false): array
|
|
{
|
|
$changed = false;
|
|
$canonicalArchivePath = $amministratore->getArchivePath();
|
|
$currentArchivePath = (string) ($amministratore->cartella_dati ?? '');
|
|
$needsArchiveSync = $force
|
|
|| $currentArchivePath === ''
|
|
|| ! is_dir($currentArchivePath)
|
|
|| $this->normalizePath($currentArchivePath) !== $this->normalizePath($canonicalArchivePath);
|
|
|
|
// 1. Cartelle
|
|
if ($needsArchiveSync) {
|
|
$amministratore->cartella_dati = null;
|
|
$amministratore->provisionArchiveIfMissing();
|
|
if ($amministratore->cartella_dati !== $canonicalArchivePath) {
|
|
$amministratore->cartella_dati = $canonicalArchivePath;
|
|
$amministratore->saveQuietly();
|
|
}
|
|
$changed = true;
|
|
}
|
|
|
|
// 2. Database dedicato
|
|
$dbName = $amministratore->getDatabaseName();
|
|
if ($createDatabase && $this->ensureDatabaseExists($dbName)) {
|
|
$changed = true;
|
|
}
|
|
|
|
// 3. Flag provisioned_at
|
|
$hasProvisionedAtColumn = Schema::hasColumn($amministratore->getTable(), 'provisioned_at');
|
|
if ($hasProvisionedAtColumn && ($changed || $force || ! $amministratore->provisioned_at)) {
|
|
$amministratore->provisioned_at = now();
|
|
$amministratore->saveQuietly();
|
|
}
|
|
|
|
return [
|
|
'amministratore_id' => $amministratore->id,
|
|
'database' => $dbName,
|
|
'archive_path' => $amministratore->cartella_dati,
|
|
'provisioned_at' => $hasProvisionedAtColumn ? $amministratore->provisioned_at : null,
|
|
'changed' => $changed,
|
|
];
|
|
}
|
|
|
|
protected function normalizePath(?string $path): string
|
|
{
|
|
$value = trim((string) $path);
|
|
if ($value === '') {
|
|
return '';
|
|
}
|
|
|
|
$resolved = realpath($value);
|
|
|
|
return $resolved !== false ? $resolved : rtrim(str_replace('\\', '/', $value), '/');
|
|
}
|
|
|
|
protected function ensureDatabaseExists(string $dbName): bool
|
|
{
|
|
try {
|
|
$exists = DB::select("SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = ?", [$dbName]);
|
|
if (! $exists) {
|
|
DB::statement("CREATE DATABASE `{$dbName}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
|
|
Log::info('[Provisioning] Created database: ' . $dbName);
|
|
return true;
|
|
}
|
|
} catch (\Throwable $e) {
|
|
Log::error('[Provisioning] Error ensuring database ' . $dbName . ': ' . $e->getMessage());
|
|
}
|
|
return false;
|
|
}
|
|
}
|