Lines n/a 0 / 0
Methods n/a 0 / 0
Classes n/a 0 / 0
Name Lines Methods CRAP
 startExecuteSqlFile n/a 0 / 0 n/a 0 / 0 7
 executeSql n/a 0 / 0 n/a 0 / 0 1
 startUsingDatabase n/a 0 / 0 n/a 0 / 0 3
 startTestDataImport n/a 0 / 0 n/a 0 / 0 1
 startConfigDataImport n/a 0 / 0 n/a 0 / 0 1
 startMigrations n/a 0 / 0 n/a 0 / 0 4
 executeTestData n/a 0 / 0 n/a 0 / 0 2
 openSqlFileHandle n/a 0 / 0 n/a 0 / 0 2
 readDelimiterDirective n/a 0 / 0 n/a 0 / 0 2
 lineEndsWithStatementDelimiter n/a 0 / 0 n/a 0 / 0 2
 filterMigrationFilesByPhase n/a 0 / 0 n/a 0 / 0 5
 extractSqlStatement n/a 0 / 0 n/a 0 / 0 2
 executeSqlStatement n/a 0 / 0 n/a 0 / 0 3
 applyDatabaseNameToConnection n/a 0 / 0 n/a 0 / 0 2
 resolveMigrationFileList n/a 0 / 0 n/a 0 / 0 2
 literalGlob n/a 0 / 0 n/a 0 / 0 1
 localReadablePath n/a 0 / 0 n/a 0 / 0 2
 localDirectory n/a 0 / 0 n/a 0 / 0 2
 localPath n/a 0 / 0 n/a 0 / 0 4
9class Db
10{
11    public static $baseDSN = '';
12
13    public static function startExecuteSqlFile(string $file, ?string $databaseName = null, bool $verbose = true): void
14    {
15        $databaseConnection = self::startUsingDatabase($databaseName, $verbose);
16        $startedAt = microtime(true);
17        $sqlFileHandle = self::openSqlFileHandle($file);
18
19        if ($verbose) {
20            \App::$log->info('Importing SQL file', ['file' => basename($file)]);
21        }
22
23        $statementDelimiter = ';';
24        $statementBuffer = '';
25
26        while ($line = $sqlFileHandle['readLine']($sqlFileHandle['handle'])) {
27            $delimiterFromLine = self::readDelimiterDirective($line);
28            if ($delimiterFromLine !== null) {
29                $statementDelimiter = $delimiterFromLine;
30                continue;
31            }
32
33            $statementBuffer .= $line;
34            if (!self::lineEndsWithStatementDelimiter($line, $statementDelimiter)) {
35                continue;
36            }
37
38            $sqlStatement = self::extractSqlStatement($statementBuffer, $statementDelimiter);
39            $statementBuffer = '';
40
41            if ($sqlStatement === '') {
42                continue;
43            }
44
45            self::executeSqlStatement($databaseConnection, $sqlStatement, $file, $verbose);
46        }
47
48        $sqlFileHandle['close']($sqlFileHandle['handle']);
49
50        if ($verbose) {
51            \App::$log->info('SQL import finished', [
52                'file' => basename($file),
53                'seconds' => round(microtime(true) - $startedAt, 3),
54            ]);
55        }
56    }
57
58    /**
59     * @psalm-api
60     */
61    public static function executeSql(string $query, ?string $databaseName = null): void
62    {
63        $databaseConnection = self::startUsingDatabase($databaseName, false);
64        $databaseConnection->exec($query);
65    }
66
67    /**
68     * @param null|string $databaseName
69     *
70     */
71    public static function startUsingDatabase(string|null $databaseName = null, bool $verbose = true): \BO\Zmsbackend\Connection\Pdo
72    {
73        if (!self::$baseDSN) {
74            self::$baseDSN = \BO\Zmsbackend\Connection\Select::$writeSourceName;
75        }
76
77        \BO\Zmsbackend\Connection\Select::closeWriteConnection();
78        self::applyDatabaseNameToConnection($databaseName);
79
80        if ($verbose) {
81            \App::$log->info('Using database connection', [
82                'dsn' => \BO\Zmsbackend\Connection\Select::$writeSourceName,
83            ]);
84        }
85
86        return \BO\Zmsbackend\Connection\Select::getWriteConnection();
87    }
88
89    public static function startTestDataImport(string $fixturesDirectory, string $filename = 'mysql_zmsbo.sql'): void
90    {
91        $defaultDatabaseName = \BO\Zmsbackend\Connection\Select::$dbname_zms;
92
93        $databaseConnection = self::startUsingDatabase('information_schema');
94        $databaseConnection->exec("DROP DATABASE IF EXISTS `$defaultDatabaseName`;");
95        $databaseConnection->exec("CREATE DATABASE IF NOT EXISTS `$defaultDatabaseName`;");
96
97        self::startExecuteSqlFile($fixturesDirectory . '/' . $filename);
98    }
99
100    public static function startConfigDataImport(): void
101    {
102        $defaults = new \BO\Zmsentities\Config();
103        (new \BO\Zmsbackend\Config\Service\Config())->updateEntity($defaults);
104    }
105
106    public static function startMigrations(string|array $migrationList, bool $commit = true, ?string $phase = null): int
107    {
108        $migrationFiles = self::resolveMigrationFileList($migrationList);
109        $migrationFiles = self::filterMigrationFilesByPhase($migrationFiles, $phase);
110        $databaseConnection = self::startUsingDatabase();
111        $completedMigrations = $databaseConnection->fetchPairs(
112            'SELECT filename, changeTimestamp FROM migrations'
113        );
114        $addedMigrationCount = 0;
115
116        foreach ($migrationFiles as $migrationFile) {
117            $migrationFilename = basename($migrationFile);
118            if (array_key_exists($migrationFilename, $completedMigrations)) {
119                continue;
120            }
121
122            $addedMigrationCount++;
123            if (!$commit) {
124                \App::$log->info('Pending migration', [
125                    'index' => $addedMigrationCount,
126                    'migration' => $migrationFilename,
127                ]);
128                continue;
129            }
130
131            self::startExecuteSqlFile($migrationFile);
132            $databaseConnection->prepare('INSERT INTO `migrations` SET `filename` = :filename')
133                ->execute(['filename' => $migrationFilename]);
134        }
135
136        \App::$log->info('Migration check finished', [
137            'completed' => count($completedMigrations),
138            'added' => $addedMigrationCount,
139        ]);
140
141        return $addedMigrationCount;
142    }
143
144    /**
145     * @return void
146     */
147    public static function executeTestData(string $testName, string $step)
148    {
149        $fixturesDirectory = realpath(__DIR__ . '/../../../tests/Zmsbackend/Service/fixtures/');
150        $sqlFile = $fixturesDirectory . '/' . $testName . '/' . $step . '.sql';
151
152        if (!file_exists($sqlFile)) {
153            return;
154        }
155
156        self::startExecuteSqlFile($sqlFile, null, false);
157    }
158
159    private static function openSqlFileHandle(string $file): array
160    {
161        $isGzipCompressed = substr($file, -3) === '.gz';
162        $file = self::localReadablePath($file);
163
164        if ($isGzipCompressed) {
165            return [
166                'handle' => gzopen($file, 'r'),
167                'readLine' => 'gzgets',
168                'close' => 'gzclose',
169            ];
170        }
171
172        return [
173            'handle' => fopen($file, 'r'),
174            'readLine' => 'fgets',
175            'close' => 'fclose',
176        ];
177    }
178
179    private static function readDelimiterDirective(string $line): ?string
180    {
181        if (!preg_match('/^\s*DELIMITER\s+(\S+)\s*$/i', rtrim($line), $matches)) {
182            return null;
183        }
184
185        return $matches[1];
186    }
187
188    private static function lineEndsWithStatementDelimiter(string $line, string $statementDelimiter): bool
189    {
190        if ($statementDelimiter === ';') {
191            return (bool) preg_match('/;\s*$/', $line);
192        }
193
194        return (bool) preg_match(
195            '/' . preg_quote($statementDelimiter, '/') . '\s*$/',
196            rtrim($line)
197        );
198    }
199
200    /**
201     * Split migrations into expand/contract phases by filename for zero-downtime
202     * (Expand–Contract) deployments.
203     *
204     * - contract phase: files whose name contains "-contract-" or "-contract." (destructive cleanup)
205     * - expand phase:   every other file, i.e. "*-expand-*" plus unprefixed additive migrations
206     * - no phase (null/empty): all files, preserving the legacy behaviour
207     */
208    private static function filterMigrationFilesByPhase(array $migrationFiles, ?string $phase): array
209    {
210        if ($phase === null || $phase === '') {
211            return $migrationFiles;
212        }
213
214        $isContract = static function (string $migrationFile): bool {
215            return (bool) preg_match('/-contract[-.]/', basename($migrationFile));
216        };
217
218        if ($phase === 'contract') {
219            return array_values(array_filter($migrationFiles, $isContract));
220        }
221
222        if ($phase === 'expand') {
223            return array_values(array_filter(
224                $migrationFiles,
225                static fn(string $migrationFile): bool => !$isContract($migrationFile)
226            ));
227        }
228
229        throw new \InvalidArgumentException(
230            "Unknown migration phase '$phase'; expected 'expand' or 'contract'"
231        );
232    }
233
234    private static function extractSqlStatement(string $statementBuffer, string $statementDelimiter): string
235    {
236        $sqlStatement = $statementBuffer;
237
238        if ($statementDelimiter !== ';') {
239            $sqlStatement = preg_replace(
240                '/' . preg_quote($statementDelimiter, '/') . '\s*$/',
241                '',
242                $sqlStatement
243            );
244        }
245
246        return trim($sqlStatement);
247    }
248
249    private static function executeSqlStatement(
250        \BO\Zmsbackend\Connection\Pdo $databaseConnection,
251        string $sqlStatement,
252        string $sourceFile,
253        bool $verbose
254    ): void {
255        try {
256            $databaseConnection->exec($sqlStatement);
257        } catch (\Exception $exception) {
258            if ($verbose) {
259                \App::$log->error('SQL import failed', [
260                    'file' => basename($sourceFile),
261                    'method' => __METHOD__,
262                    'exception' => get_class($exception),
263                    'message' => $exception->getMessage(),
264                    'code' => $exception->getCode(),
265                ]);
266            }
267
268            throw $exception;
269        }
270    }
271
272    private static function applyDatabaseNameToConnection(?string $databaseName): void
273    {
274        if ($databaseName === null) {
275            \BO\Zmsbackend\Connection\Select::$writeSourceName = self::$baseDSN;
276            return;
277        }
278
279        $defaultDatabaseName = \BO\Zmsbackend\Connection\Select::$dbname_zms;
280        \BO\Zmsbackend\Connection\Select::$writeSourceName = preg_replace(
281            "#dbname=$defaultDatabaseName.*?;#",
282            "dbname=$databaseName;",
283            self::$baseDSN
284        );
285    }
286
287    private static function resolveMigrationFileList(string|array $migrationList): array
288    {
289        if (!is_array($migrationList)) {
290            $migrationList = glob(self::literalGlob(self::localDirectory($migrationList)) . '/*.sql');
291        }
292
293        sort($migrationList);
294
295        return $migrationList;
296    }
297
298    private static function literalGlob(string $path): string
299    {
300        return preg_replace('/([*?\[\]\\\\])/', '\\\\$1', $path) ?? $path;
301    }
302
303    /**
304     * @psalm-taint-escape file
305     * @psalm-taint-escape ssrf
306     */
307    private static function localReadablePath(string $path): string
308    {
309        $real = self::localPath($path);
310        if (!is_file($real)) {
311            throw new \InvalidArgumentException('SQL file is not a local file');
312        }
313
314        return $real;
315    }
316
317    /**
318     * @psalm-taint-escape file
319     * @psalm-taint-escape ssrf
320     */
321    private static function localDirectory(string $path): string
322    {
323        $real = self::localPath($path);
324        if (!is_dir($real)) {
325            throw new \InvalidArgumentException('Migration directory is not a local directory');
326        }
327
328        return $real;
329    }
330
331    private static function localPath(string $path): string
332    {
333        $hasStreamWrapper = preg_match('#^[a-z][a-z0-9+.-]*://#i', $path) === 1;
334        $real = (!$hasStreamWrapper && !str_contains($path, "\0")) ? realpath($path) : false;
335        if ($real === false) {
336            throw new \InvalidArgumentException('Path is not on the local filesystem');
337        }
338
339        return $real;
340    }
341}