You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
100 lines
2.8 KiB
100 lines
2.8 KiB
<?php |
|
|
|
namespace App\Console\Commands; |
|
|
|
use App\Models\AppSetting; |
|
use Illuminate\Console\Command; |
|
use Illuminate\Support\Facades\Crypt; |
|
use Illuminate\Support\Facades\DB; |
|
use Illuminate\Support\Facades\Schema; |
|
use Throwable; |
|
|
|
class SyncEnvAppSettingsCommand extends Command |
|
{ |
|
protected $signature = 'app:sync-env-settings'; |
|
|
|
protected $description = 'Seed SMTP and DB connections from .env when PostgreSQL app tables are empty'; |
|
|
|
/** @var array<string, string> */ |
|
private const MAIL_ENV_MAP = [ |
|
'mail_mailer' => 'MAIL_MAILER', |
|
'mail_host' => 'MAIL_HOST', |
|
'mail_port' => 'MAIL_PORT', |
|
'mail_username' => 'MAIL_USERNAME', |
|
'mail_password' => 'MAIL_PASSWORD', |
|
'mail_encryption' => 'MAIL_ENCRYPTION', |
|
'mail_from_address' => 'MAIL_FROM_ADDRESS', |
|
'mail_from_name' => 'MAIL_FROM_NAME', |
|
]; |
|
|
|
public function handle(): int |
|
{ |
|
if (env('DB_CONNECTION') !== 'pgsql') { |
|
return self::SUCCESS; |
|
} |
|
|
|
try { |
|
if (! Schema::hasTable('app_settings')) { |
|
return self::SUCCESS; |
|
} |
|
|
|
if (DB::table('app_settings')->count() === 0) { |
|
$this->syncMailFromEnv(); |
|
} |
|
|
|
if (Schema::hasTable('database_connections') && DB::table('database_connections')->count() === 0) { |
|
$this->syncDatabaseConnectionFromEnv(); |
|
} |
|
} catch (Throwable $e) { |
|
$this->warn('Env sync failed: ' . $e->getMessage()); |
|
|
|
return self::FAILURE; |
|
} |
|
|
|
return self::SUCCESS; |
|
} |
|
|
|
private function syncMailFromEnv(): void |
|
{ |
|
$synced = 0; |
|
|
|
foreach (self::MAIL_ENV_MAP as $key => $envKey) { |
|
$value = env($envKey); |
|
|
|
if ($value === null || $value === '') { |
|
continue; |
|
} |
|
|
|
AppSetting::updateOrCreate(['key' => $key], ['value' => (string) $value]); |
|
$synced++; |
|
} |
|
|
|
if ($synced > 0) { |
|
$this->info("Synced {$synced} SMTP setting(s) from .env to PostgreSQL."); |
|
} |
|
} |
|
|
|
private function syncDatabaseConnectionFromEnv(): void |
|
{ |
|
$host = env('MSSQL_HOST'); |
|
|
|
if (! $host) { |
|
return; |
|
} |
|
|
|
DB::table('database_connections')->insert([ |
|
'name' => 'SQL Server (default)', |
|
'driver' => 'sqlsrv', |
|
'host' => $host, |
|
'port' => (int) env('MSSQL_PORT', 1433), |
|
'database' => env('MSSQL_DATABASE', 'master'), |
|
'username' => env('MSSQL_USERNAME', 'sa'), |
|
'password_encrypted' => Crypt::encryptString(env('MSSQL_PASSWORD', '')), |
|
'is_active' => true, |
|
'created_at' => now(), |
|
'updated_at' => now(), |
|
]); |
|
|
|
$this->info('Seeded default SQL Server connection from .env.'); |
|
} |
|
}
|
|
|