Completed
Pull Request — master (#3)
by Rémy
01:33
created

Helper   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Importance

Changes 0
Metric Value
wmc 12
lcom 0
cbo 0
dl 0
loc 57
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A isMySQL() 0 4 1
A isSQLite() 0 4 1
C quote() 0 25 8
A getIdentifierQuoter() 0 14 2
1
<?php
2
/**
3
 * @author Rémy M. Böhler <[email protected]>
4
 */
5
declare(strict_types=1);
6
7
namespace Rorm;
8
9
class Helper
10
{
11
    public function isMySQL(\PDO $dbh): bool
12
    {
13
        return $dbh->getAttribute(\PDO::ATTR_DRIVER_NAME) === 'mysql';
14
    }
15
16
    public function isSQLite(\PDO $dbh): bool
17
    {
18
        return $dbh->getAttribute(\PDO::ATTR_DRIVER_NAME) === 'sqlite';
19
    }
20
21
    public function quote(\PDO $dbh, $value)
22
    {
23
        if (is_bool($value)) {
24
            /**
25
             * MySQL has true and false literals
26
             * SQLite does not support boolean type nor literals
27
             */
28
            if ($this->isMySQL($dbh)) {
29
                return $value ? 'TRUE' : 'FALSE';
30
            }
31
32
            return $value ? 1 : 0;
33
        }
34
        if ($value === null) {
35
            return 'NULL';
36
        }
37
        if (is_int($value)) {
38
            return (int)$value;
39
        }
40
        if (is_float($value)) {
41
            return (float)$value;
42
        }
43
44
        return $dbh->quote($value);
45
    }
46
47
    /**
48
     * Method to quote identifiers
49
     * Please make sure you keep the quoter as long you are needing it.
50
     */
51
    public function getIdentifierQuoter(\PDO $dbh): callable
52
    {
53
        if ($this->isMySQL($dbh)) {
54
            // mysql mode
55
            return function ($identifier) {
56
                return '`' . str_replace('`', '``', $identifier) . '`';
57
            };
58
        }
59
60
        // standard sql mode
61
        return function ($identifier) {
62
            return '"' . str_replace('"', '""', $identifier) . '"';
63
        };
64
    }
65
}
66