Completed
Push — master ( 4a880b...4a9e4f )
by Emmanuel
21:39 queued 20:01
created

DBUtils::getCondition()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 26
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 2

Importance

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