49 lines
1.2 KiB
PHP
49 lines
1.2 KiB
PHP
<?php
|
|
|
|
namespace Tests\Support;
|
|
|
|
use Config\Database;
|
|
use Throwable;
|
|
|
|
class DBReset
|
|
{
|
|
private const DB_GROUP = 'tests';
|
|
|
|
protected static array $excludeTables = ['migrations', 'school_years'];
|
|
|
|
public static function resetDatabase(): void
|
|
{
|
|
$config = config('Database');
|
|
$dbConfig = $config->{self::DB_GROUP} ?? [];
|
|
|
|
try {
|
|
$db = Database::connect(self::DB_GROUP);
|
|
$db->initialize();
|
|
} catch (Throwable $exception) {
|
|
throw new \RuntimeException(
|
|
sprintf(
|
|
'Test database connection failed: group=%s host=%s port=%s database=%s',
|
|
self::DB_GROUP,
|
|
$dbConfig['hostname'] ?? '',
|
|
$dbConfig['port'] ?? '',
|
|
$dbConfig['database'] ?? ''
|
|
),
|
|
0,
|
|
$exception
|
|
);
|
|
}
|
|
|
|
$db->disableForeignKeyChecks();
|
|
|
|
$tables = $db->listTables();
|
|
|
|
foreach ($tables as $table) {
|
|
if (!in_array($table, self::$excludeTables)) {
|
|
$db->query('TRUNCATE TABLE ' . $db->escapeIdentifiers($table));
|
|
}
|
|
}
|
|
|
|
$db->enableForeignKeyChecks();
|
|
}
|
|
}
|