Passed
Push — master ( 88983b...1e7624 )
by Wilmer
02:43
created

DbHelper::replaceQuotes()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
eloc 6
c 1
b 1
f 0
dl 0
loc 8
rs 10
cc 1
nc 1
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\ActiveRecord\Tests\Support;
6
7
use Yiisoft\Db\Driver\PDO\ConnectionPDOInterface;
8
use Yiisoft\Db\Exception\Exception;
9
use Yiisoft\Db\Exception\InvalidConfigException;
10
11
use function explode;
12
use function file_get_contents;
13
use function preg_replace;
14
use function str_replace;
15
use function trim;
16
17
final class DbHelper
18
{
19
    /**
20
     * Loads the fixture into the database.
21
     *
22
     * @throws Exception
23
     * @throws InvalidConfigException
24
     */
25
    public static function loadFixture(ConnectionPDOInterface $db): void
26
    {
27
        $driverName = $db->getName();
28
29
        $fixture = match ($driverName) {
30
            'mysql' => dirname(__DIR__) . '/data/mysql.sql',
31
            'oci' => dirname(__DIR__) . '/data/oci.sql',
32
            'pgsql' => dirname(__DIR__) . '/data/pgsql.sql',
33
            'sqlite' => dirname(__DIR__) . '/data/sqlite.sql',
34
            'sqlsrv' => dirname(__DIR__) . '/data/mssql.sql',
35
        };
36
37
        if ($db->isActive()) {
38
            $db->close();
39
        }
40
41
        $db->open();
42
43
        if ($driverName === 'oci') {
44
            [$drops, $creates] = explode('/* STATEMENTS */', file_get_contents($fixture), 2);
45
            [$statements, $triggers, $data] = explode('/* TRIGGERS */', $creates, 3);
46
            $lines = array_merge(
47
                explode('--', $drops),
48
                explode(';', $statements),
49
                explode('/', $triggers),
50
                explode(';', $data)
51
            );
52
        } else {
53
            $lines = explode(';', file_get_contents($fixture));
54
        }
55
56
        foreach ($lines as $line) {
57
            if (trim($line) !== '') {
58
                $db->getPDO()->exec($line);
59
            }
60
        }
61
    }
62
63
    /**
64
     * Adjust dbms specific escaping.
65
     *
66
     * @param string $sql string SQL statement to adjust.
67
     * @param string $driverName string DBMS name.
68
     *
69
     * @return mixed
70
     */
71
    public static function replaceQuotes(string $sql, string $driverName): string
72
    {
73
        return match ($driverName) {
74
            'mysql', 'sqlite' => str_replace(['[[', ']]'], '`', $sql),
75
            'oci' => str_replace(['[[', ']]'], '"', $sql),
76
            'pgsql' => str_replace(['\\[', '\\]'], ['[', ']'], preg_replace('/(\[\[)|((?<!(\[))]])/', '"', $sql)),
77
            'db', 'sqlsrv' => str_replace(['[[', ']]'], ['[', ']'], $sql),
78
            default => $sql,
79
        };
80
    }
81
}
82