Passed
Push — master ( 8807b4...37e483 )
by Wilmer
03:08
created

DbHelper   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 14
c 1
b 0
f 0
dl 0
loc 51
rs 10
wmc 7

5 Methods

Rating   Name   Duplication   Size   Complexity  
A replaceQuotes() 0 8 1
A loadFixture() 0 8 3
A getQueryCache() 0 3 1
A getSchemaCache() 0 3 1
A getCache() 0 3 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Tests\Support;
6
7
use Yiisoft\Cache\ArrayCache;
8
use Yiisoft\Cache\Cache;
9
use Yiisoft\Cache\CacheInterface;
10
use Yiisoft\Db\Cache\QueryCache;
11
use Yiisoft\Db\Cache\SchemaCache;
12
use Yiisoft\Db\Driver\PDO\ConnectionPDOInterface;
13
use Yiisoft\Db\Exception\Exception;
14
use Yiisoft\Db\Exception\InvalidConfigException;
15
16
use function explode;
17
use function file_get_contents;
18
use function preg_replace;
19
use function str_replace;
20
use function trim;
21
22
final class DbHelper
23
{
24
    public static function getCache(): CacheInterface
25
    {
26
        return new Cache(new ArrayCache());
27
    }
28
29
    public static function getQueryCache(): QueryCache
30
    {
31
        return new QueryCache(self::getCache());
32
    }
33
34
    public static function getSchemaCache(): SchemaCache
35
    {
36
        return new SchemaCache(self::getCache());
37
    }
38
39
    /**
40
     * Loads the fixture into the database.
41
     *
42
     * @throws Exception
43
     * @throws InvalidConfigException
44
     */
45
    public static function loadFixture(ConnectionPDOInterface $db, string $fixture): void
46
    {
47
        $db->open();
48
        $lines = explode(';', file_get_contents($fixture));
49
50
        foreach ($lines as $line) {
51
            if (trim($line) !== '') {
52
                $db->getPDO()?->exec($line);
53
            }
54
        }
55
    }
56
57
    /**
58
     * Adjust dbms specific escaping.
59
     *
60
     * @param string $sql string SQL statement to adjust.
61
     * @param string $driverName string DBMS name.
62
     *
63
     * @return mixed
64
     */
65
    public static function replaceQuotes(string $sql, string $driverName): string
66
    {
67
        return match ($driverName) {
68
            'mysql', 'sqlite' => str_replace(['[[', ']]'], '`', $sql),
69
            'oci' => str_replace(['[[', ']]'], '"', $sql),
70
            'pgsql' => str_replace(['\\[', '\\]'], ['[', ']'], preg_replace('/(\[\[)|((?<!(\[))]])/', '"', $sql)),
71
            'db', 'sqlsrv' => str_replace(['[[', ']]'], ['[', ']'], $sql),
72
            default => $sql,
73
        };
74
    }
75
}
76