Passed
Push — master ( cef086...22be2e )
by Emmanuel
01:44
created

DBUtils::getTableCols()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 14
ccs 0
cts 13
cp 0
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 9
nc 2
nop 1
crap 6
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
    public function __construct(Connection $conn)
40
    {
41
        $this->conn = $conn;
42
    }
43
44
45
    /**
46
     * Do a simple count for a table
47
     * @param  string $table
48
     * @return int
49
     */
50
    public function countResults(string $table): int
51
    {
52
        $queryBuilder = $this->conn->createQueryBuilder();
53
        $rows = $queryBuilder->select('COUNT(1)')->from($table)->execute();
54
55
        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
    public function getPrimaryKey(string $table): string
65
    {
66
        $schema = $this->conn->getSchemaManager();
67
        $tableDetails = $schema->listTableDetails($table);
68
        if ($tableDetails->hasPrimaryKey() === false) {
69
            throw new NeuralizerException("Can't find a primary key for '{$table}'");
70
        }
71
72
        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
    public function getTableCols(string $table): array
82
    {
83
        $schema = $this->conn->getSchemaManager();
84
        $tableCols = $schema->listTableColumns($table);
85
        $cols = [];
86
        foreach ($tableCols as $col) {
87
            $cols[$col->getName()] = [
88
                'length' => $col->getLength(),
89
                'type'   => $col->getType(),
90
                'unsigned' => $col->getUnsigned(),
91
            ];
92
        }
93
94
        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
    public function getRawSQL(QueryBuilder $queryBuilder)
104
    {
105
        $sql = $queryBuilder->getSQL();
106
        foreach ($queryBuilder->getParameters() as $parameter => $value) {
107
            $sql = str_replace($parameter, "'$value'", $sql);
108
        }
109
110
        return $sql;
111
    }
112
113
    /**
114
     * Make sure a table exists
115
     * @param  string $table [description]
116
     */
117
    public function assertTableExists(string $table): void
118
    {
119
        if ($this->conn->getSchemaManager()->tablesExist([$table]) === false) {
120
            throw new NeuralizerException("Table $table does not exist");
121
        }
122
    }
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
    public function getCondition(string $field, array $fieldConf): string
133
    {
134
        $type = strtolower($fieldConf['type']);
135
        $unsigned = $fieldConf['unsigned'];
136
137
        $integerCast = $this->getIntegerCast($unsigned);
138
139
        $condition = "(CASE $field WHEN NULL THEN NULL ELSE :$field END)";
140
141
        $typeToCast = [
142
            'date'     => 'DATE',
143
            'datetime' => 'DATE',
144
            'time'     => 'TIME',
145
            'smallint' => $integerCast,
146
            'integer'  => $integerCast,
147
            'bigint'   => $integerCast,
148
            'float'    => 'DECIMAL',
149
            'decimal'  => 'DECIMAL',
150
        ];
151
152
        // No cast required
153
        if (!array_key_exists($type, $typeToCast)) {
154
            return $condition;
155
        }
156
157
        return "CAST($condition AS {$typeToCast[$type]})";
158
    }
159
160
161
    /**
162
     * Get the right CAST for an INTEGER
163
     *
164
     * @param  bool   $unsigned
165
     * @return string
166
     */
167
    private function getIntegerCast(bool $unsigned): string
168
    {
169
        $driver = $this->conn->getDriver();
170
        if (strpos($driver->getName(), 'mysql')) {
171
            return $unsigned === true ? 'UNSIGNED' : 'SIGNED';
172
        }
173
174
        return 'INTEGER';
175
    }
176
}
177