Completed
Pull Request — master (#332)
by Elan
45:53 queued 44:29
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
use PDOStatement;
8
9
class PdoWrapper extends PDO
10
{
11
    /** @var string */
12
    private $quoteIdentifier;
13
14
    public static function create(array $options): self
15
    {
16
        $pdoOptions = [
17
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
18
        ];
19
        $pdo = new self(
20
            $options['dsn'],
21
            $options['user'],
22
            $options['pass'],
23
            $pdoOptions
24
        );
25
26
        $pdo->quoteIdentifier = self::getQuoteIdentifier($options['dsn']);
27
28
        return $pdo;
29
    }
30
31
    /**
32
     * Replace placeholders surrounded by {} with values from $params.
33
     */
34
    public function prepareTemplate(string $template, array $params): ?PDOStatement
35
    {
36
        $keys = array_map(static function ($value) {
37
            return sprintf("{%s}", $value);
38
        }, array_keys($params));
39
        $query = str_replace($keys, array_values($params), $template);
40
41
        return $this->prepare($query) ?: null;
42
    }
43
44
    public function quoteIdentifier(string $identifier)
45
    {
46
        return sprintf('%c%s%c', $this->quoteIdentifier, $identifier, $this->quoteIdentifier);
47
    }
48
49
    public function quoteIdentifiers(array $identifiers)
50
    {
51
        $result = [];
52
        foreach ($identifiers as $identifier) {
53
            $result[] = $this->quoteIdentifier($identifier);
54
        }
55
56
        return implode(",", $result);
57
    }
58
59
    private static function getQuoteIdentifier(string $dsn): string
60
    {
61
        $adapter = explode(':', $dsn, 2)[0];
62
        $identifierMap = [
63
            'mysql' => '`',
64
            'pgsql' => '"',
65
            'sqlite' => '"',
66
        ];
67
        $quoteIdentifier = $identifierMap[$adapter] ?? null;
68
69
        if ($quoteIdentifier === null) {
70
            throw new PdoException("Unsupported adapter '$adapter' to detect quote identifier");
71
        }
72
73
        return $quoteIdentifier;
74
    }
75
}
76