Completed
Pull Request — master (#332)
by Elan
01:13
created

PdoWrapper::create()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 16
rs 9.7333
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
namespace Xhgui\Db;
4
5
use PDO;
6
use PDOException;
7
8
class PdoWrapper extends PDO
9
{
10
    /** @var string */
11
    private $quoteIdentifier;
12
13
    public static function create(array $options): self
14
    {
15
        $pdoOptions = [
16
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
17
        ];
18
        $pdo = new self(
19
            $options['dsn'],
20
            $options['user'],
21
            $options['pass'],
22
            $pdoOptions
23
        );
24
25
        $pdo->quoteIdentifier = self::getQuoteIdentifier($options['dsn']);
26
27
        return $pdo;
28
    }
29
30
    public function quoteIdentifier(string $identifier)
31
    {
32
        return sprintf('%c%s%c', $this->quoteIdentifier, $identifier, $this->quoteIdentifier);
33
    }
34
35
    private static function getQuoteIdentifier(string $dsn): string
36
    {
37
        $adapter = explode(':', $dsn, 2)[0];
38
        $identifierMap = [
39
            'mysql' => '`',
40
            'pgsql' => '"',
41
            'sqlite' => '"',
42
        ];
43
        $quoteIdentifier = $identifierMap[$adapter] ?? null;
44
45
        if ($quoteIdentifier === null) {
46
            throw new PdoException("Unsupported adapter '$adapter' to detect quote identifier");
47
        }
48
49
        return $quoteIdentifier;
50
    }
51
}
52