Passed
Push — master ( 16eb74...e2e5d8 )
by Emmanuel
02:58
created

DBUtils   A

Complexity

Total Complexity 17

Size/Duplication

Total Lines 176
Duplicated Lines 0 %

Test Coverage

Coverage 96.61%

Importance

Changes 0
Metric Value
wmc 17
dl 0
loc 176
ccs 57
cts 59
cp 0.9661
rs 10
c 0
b 0
f 0

9 Methods

Rating   Name   Duplication   Size   Complexity  
A getTableCols() 0 14 2
A getRawSQL() 0 8 2
A getPrimaryKey() 0 9 2
A countResults() 0 6 1
A __construct() 0 3 1
A assertTableExists() 0 4 2
B getCondition() 0 26 2
A getEmptyValue() 0 20 2
A getIntegerCast() 0 8 3
1
<?php
2
/**
3
 * neuralyzer : Data Anonymization Library and CLI Tool
4
 *
5
 * PHP Version 7.1
6
 *
7
 * @author Emmanuel Dyan
8
 * @author Rémi Sauvat
9
 * @copyright 2018 Emmanuel Dyan
10
 *
11
 * @package edyan/neuralyzer
12
 *
13
 * @license GNU General Public License v2.0
14
 *
15
 * @link https://github.com/edyan/neuralyzer
16
 */
17
18
namespace Edyan\Neuralyzer\Utils;
19
20
use Doctrine\DBAL\Connection;
21
use Doctrine\DBAL\Query\QueryBuilder;
22
use Edyan\Neuralyzer\Exception\NeuralizerException;
23
24
/**
25
 * A few generic methods to help interacting with DB
26
 */
27
class DBUtils
28
{
29
    /**
30
     * Doctrine DBAL Connection
31
     * @var Connection
32
     */
33
    private $conn;
34
35
    /**
36
     * Set the connection (dependency)
37
     * @param Connection $conn
38
     */
39 56
    public function __construct(Connection $conn)
40
    {
41 56
        $this->conn = $conn;
42 56
    }
43
44
45
    /**
46
     * Do a simple count for a table
47
     * @param  string $table
48
     * @return int
49
     */
50 22
    public function countResults(string $table): int
51
    {
52 22
        $queryBuilder = $this->conn->createQueryBuilder();
53 22
        $rows = $queryBuilder->select('COUNT(1)')->from($table)->execute();
54
55 20
        return (int)$rows->fetch(\Doctrine\DBAL\FetchMode::NUMERIC)[0];
56
    }
57
58
59
    /**
60
     * Identify the primary key for a table
61
     * @param  string $table
62
     * @return string Field's name
63
     */
64 29
    public function getPrimaryKey(string $table): string
65
    {
66 29
        $schema = $this->conn->getSchemaManager();
67 29
        $tableDetails = $schema->listTableDetails($table);
68 29
        if ($tableDetails->hasPrimaryKey() === false) {
69 2
            throw new NeuralizerException("Can't find a primary key for '{$table}'");
70
        }
71
72 27
        return $tableDetails->getPrimaryKey()->getColumns()[0];
73
    }
74
75
76
    /**
77
     * Retrieve columns list for a table with type and length
78
     * @param  string $table
79
     * @return array $cols
80
     */
81 30
    public function getTableCols(string $table): array
82
    {
83 30
        $schema = $this->conn->getSchemaManager();
84 30
        $tableCols = $schema->listTableColumns($table);
85 30
        $cols = [];
86 30
        foreach ($tableCols as $col) {
87 30
            $cols[$col->getName()] = [
88 30
                'length' => $col->getLength(),
89 30
                'type'   => $col->getType(),
90 30
                'unsigned' => $col->getUnsigned(),
91
            ];
92
        }
93
94 30
        return $cols;
95
    }
96
97
98
    /**
99
     * To debug, build the final SQL (can be approximative)
100
     * @param  QueryBuilder $queryBuilder
101
     * @return string
102
     */
103 11
    public function getRawSQL(QueryBuilder $queryBuilder)
104
    {
105 11
        $sql = $queryBuilder->getSQL();
106 11
        foreach ($queryBuilder->getParameters() as $parameter => $value) {
107 10
            $sql = str_replace($parameter, "'$value'", $sql);
108
        }
109
110 11
        return $sql;
111
    }
112
113
    /**
114
     * Make sure a table exists
115
     * @param  string $table [description]
116
     */
117 30
    public function assertTableExists(string $table): void
118
    {
119 30
        if ($this->conn->getSchemaManager()->tablesExist([$table]) === false) {
120 2
            throw new NeuralizerException("Table $table does not exist");
121
        }
122 28
    }
123
124
125
    /**
126
     * Build the condition by casting the value if needed
127
     *
128
     * @param  string $field
129
     * @param  array  $fieldConf   Various values about the field
130
     * @return string
131
     */
132 13
    public function getCondition(string $field, array $fieldConf): string
133
    {
134 13
        $type = strtolower($fieldConf['type']);
135 13
        $unsigned = $fieldConf['unsigned'];
136
137 13
        $integerCast = $this->getIntegerCast($unsigned);
138
139 13
        $condition = "(CASE $field WHEN NULL THEN NULL ELSE :$field END)";
140
141
        $typeToCast = [
142 13
            'date'     => 'DATE',
143 13
            'datetime' => 'DATE',
144 13
            'time'     => 'TIME',
145 13
            'smallint' => $integerCast,
146 13
            'integer'  => $integerCast,
147 13
            'bigint'   => $integerCast,
148 13
            'float'    => 'DECIMAL',
149 13
            'decimal'  => 'DECIMAL',
150
        ];
151
152
        // No cast required
153 13
        if (!array_key_exists($type, $typeToCast)) {
154 11
            return $condition;
155
        }
156
157 12
        return "CAST($condition AS {$typeToCast[$type]})";
158
    }
159
160
161
    /**
162
     * Gives an empty value according to the field (example : numeric = 0)
163
     * @param  string $type
164
     * @return mixed
165
     */
166 8
    public function getEmptyValue(string $type)
167
    {
168 8
        $type = strtolower($type);
169
        $typeToValue = [
170 8
            'date' => '1970-01-01',
171
            'datetime' => '1970-01-01 00:00:00',
172
            'time' => '00:00:00',
173
            'smallint' => 0,
174
            'integer'  => 0,
175
            'bigint'   => 0,
176
            'float'    => 0,
177
            'decimal'  => 0,
178
        ];
179
180
        // Value is simply an empty string
181 8
        if (!array_key_exists($type, $typeToValue)) {
182 8
            return '';
183
        }
184
185
        return $typeToValue[$type];
186
    }
187
188
189
    /**
190
     * Get the right CAST for an INTEGER
191
     *
192
     * @param  bool   $unsigned
193
     * @return string
194
     */
195 13
    private function getIntegerCast(bool $unsigned): string
196
    {
197 13
        $driver = $this->conn->getDriver();
198 13
        if (strpos($driver->getName(), 'mysql')) {
199 13
            return $unsigned === true ? 'UNSIGNED' : 'SIGNED';
200
        }
201
202
        return 'INTEGER';
203
    }
204
}
205