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

PdoWrapper   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
wmc 4
lcom 1
cbo 0
dl 0
loc 44
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A create() 0 16 1
A quoteIdentifier() 0 4 1
A getQuoteIdentifier() 0 16 2
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