Files
SGF/app/Shared/Testing/TestingDatabaseGuard.php
2026-11-11 09:00:17 +02:00

41 lines
2.5 KiB
PHP

<?php
namespace App\Shared\Testing;
use Illuminate\Support\Facades\DB;
use RuntimeException;
final class TestingDatabaseGuard
{
public static function assertSafe(?string $connection = null): void
{
if(app()->environment('budget-testing')&&config('sgf_single_installation.enabled')===true){\App\Shared\Installation\CompositionRuntime::assert($connection);return;}
$name = $connection ?: config('database.default');
$config = config("database.connections.{$name}", []);
if(app()->environment(['testing','browser-testing'])&&(config('sales_ledger.synthetic_enabled')===true||config('cost_ledger.synthetic_enabled')===true||config('industrial_ledger.synthetic_enabled')===true)
&&($config['driver']??null)==='pgsql'&&($config['host']??null)==='127.0.0.1'&&(string)($config['port']??'')==='55439'
&&preg_match('/^payable_sgf_([a-f0-9]{12})$/D',$config['database']??'',$m)&&($config['username']??null)==='payable_history_sgf_'.$m[1]
&&empty($config['url'])&&empty($config['read'])&&empty($config['write'])&&($config['search_path']??'public')==='public'){
\Tempo\Finance\GeneralLedger\LedgerSchema::assertSynthetic(DB::connection($name));
$actual=DB::connection($name)->selectOne('SELECT current_database() db,current_user role');
if($actual->db!==$config['database']||$actual->role!==$config['username'])throw new RuntimeException('SGF_TEST_DATABASE_REFUSED: configuração QA e destino efectivo divergem.');return;
}
$expected = [
'driver' => 'pgsql', 'host' => '127.0.0.1', 'port' => '55432',
'database' => 'sgf_tempo_test', 'username' => 'sgf_test_runner',
];
foreach ($expected as $key => $value) {
if ((string) ($config[$key] ?? '') !== $value) {
throw new RuntimeException('SGF_TEST_DATABASE_REFUSED: apenas sgf_tempo_test no cluster próprio é permitido.');
}
}
if (! empty($config['url']) || ! empty($config['read']) || ! empty($config['write']) || ($config['search_path'] ?? 'public') !== 'public') {
throw new RuntimeException('SGF_TEST_DATABASE_REFUSED: redireccionamento de ligação não permitido.');
}
$identity = DB::connection($name)->selectOne('SELECT current_database() AS db, current_user AS role');
if ($identity->db !== 'sgf_tempo_test' || $identity->role !== 'sgf_test_runner') {
throw new RuntimeException('SGF_TEST_DATABASE_REFUSED: destino efectivo inválido.');
}
}
}