Completed
Push — master ( 789d3b...e059a1 )
by Emmanuel
01:49
created

DBUtils::getCondition()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 26
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 26
ccs 0
cts 16
cp 0
rs 8.8571
c 0
b 0
f 0
cc 2
eloc 16
nc 2
nop 2
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 6
    public function __construct(Connection $conn)
40
    {
41 6
        $this->conn = $conn;
42 6
    }
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 3
    public function getPrimaryKey(string $table): string
65
    {
66 3
        $schema = $this->conn->getSchemaManager();
67 3
        $tableDetails = $schema->listTableDetails($table);
68 3
        if ($tableDetails->hasPrimaryKey() === false) {
69 1
            throw new NeuralizerException("Can't find a primary key for '{$table}'");
70
        }
71
72 2
        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 2
    public function getTableCols(string $table): array
82
    {
83 2
        $schema = $this->conn->getSchemaManager();
84 2
        $tableCols = $schema->listTableColumns($table);
85 2
        $cols = [];
86 2
        foreach ($tableCols as $col) {
87 2
            $cols[$col->getName()] = [
88 2
                'length' => $col->getLength(),
89 2
                'type'   => $col->getType(),
90 2
                'unsigned' => $col->getUnsigned(),
91
            ];
92
        }
93
94 2
        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 4
    public function assertTableExists(string $table)
115
    {
116 4
        $schema = $this->conn->getSchemaManager();
117 4
        if ($schema->tablesExist($table) === false) {
0 ignored issues
show
Bug introduced by
$table of type string is incompatible with the type array expected by parameter $tableNames of Doctrine\DBAL\Schema\Abs...aManager::tablesExist(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

117
        if ($schema->tablesExist(/** @scrutinizer ignore-type */ $table) === false) {
Loading history...
118 1
            throw new NeuralizerException("Table $table does not exist");
119
        }
120 3
    }
121
122
123
    /**
124
     * Build the condition by casting the value if needed
125
     *
126
     * @param  string $field
127
     * @return string
128
     */
129
    public function getCondition(string $field, array $fieldConf): string
130
    {
131
        $type = strtolower($fieldConf['type']);
132
        $unsigned = $fieldConf['unsigned'];
133
134
        $integerCast = $this->getIntegerCast($unsigned);
135
136
        $condition = "(CASE $field WHEN NULL THEN NULL ELSE :$field END)";
137
138
        $typeToCast = [
139
            'date'     => 'DATE',
140
            'datetime' => 'DATE',
141
            'time'     => 'TIME',
142
            'smallint' => $integerCast,
143
            'integer'  => $integerCast,
144
            'bigint'   => $integerCast,
145
            'float'    => 'DECIMAL',
146
            'decimal'  => 'DECIMAL',
147
        ];
148
149
        // No cast required
150
        if (!array_key_exists($type, $typeToCast)) {
151
            return $condition;
152
        }
153
154
        return "CAST($condition AS {$typeToCast[$type]})";
155
    }
156
157
158
    /**
159
     * Get the right CAST for an INTEGER
160
     *
161
     * @param  string $field
162
     * @return string
163
     */
164
    private function getIntegerCast(bool $unsigned): string
165
    {
166
        $driver = $this->conn->getDriver();
167
        if (strpos($driver->getName(), 'mysql')) {
168
            return $unsigned === true ? 'UNSIGNED' : 'SIGNED';
169
        }
170
171
        return 'INTEGER';
172
    }
173
}
174