Completed
Push — master ( ffefc4...9322fd )
by Emmanuel
04:19
created

DB   A

Complexity

Total Complexity 19

Size/Duplication

Total Lines 157
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 19
c 2
b 0
f 0
lcom 1
cbo 2
dl 0
loc 157
ccs 61
cts 61
cp 1
rs 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
C processEntity() 0 36 7
A getPrimaryKey() 0 16 3
A runUpdate() 0 13 2
A runDelete() 0 17 4
A buildUpdateSQL() 0 11 2
1
<?php
2
/**
3
 * Inet Data Anonymization
4
 *
5
 * PHP Version 5.3 -> 7.0
6
 *
7
 * @author Emmanuel Dyan
8
 * @author Rémi Sauvat
9
 * @copyright 2005-2015 iNet Process
10
 *
11
 * @package inetprocess/neuralyzer
12
 *
13
 * @license GNU General Public License v2.0
14
 *
15
 * @link http://www.inetprocess.com
16
 */
17
18
namespace Inet\Neuralyzer\Anonymizer;
19
20
use Inet\Neuralyzer\Exception\InetAnonException;
21
22
/**
23
 * DB Anonymizer
24
 */
25
class DB extends AbstractAnonymizer
26
{
27
    /**
28
     * The PDO connection
29
     *
30
     * @var \PDO
31
     */
32
    protected $pdo;
33
34
    /**
35
     * Constructor
36
     *
37
     * @param \PDO $pdo
38
     */
39 15
    public function __construct(\PDO $pdo)
40
    {
41 15
        $this->pdo = $pdo;
42 15
        $this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
43 15
    }
44
45
    /**
46
     * Process an entity by reading / writing to the DB
47
     *
48
     * @param string        $table
49
     * @param callable|null $callback
50
     * @param bool          $pretend
51
     * @param bool          $returnResult
52
     *
53
     * @return void|array
54
     */
55 13
    public function processEntity($table, $callback = null, $pretend = true, $returnResult = false)
56
    {
57 13
        $key = $this->getPrimaryKey($table);
58
59 11
        if ($this->whatToDoWithEntity($table) === self::TRUNCATE_TABLE) {
60 4
            $where = $this->getWhereConditionInConfig($table);
61 4
            $query = $this->runDelete($table, $where, $pretend);
62
63 3
            return ($returnResult === true ? array($query) : '');
64
        }
65
66
        // I need to read line by line if I have to update the table
67
        // to make sure I do update by update (slower but no other choice for now)
68 5
        $res = $this->pdo->query("SELECT $key FROM $table");
69
70 5
        $res->setFetchMode(\PDO::FETCH_ASSOC);
71 5
        $i = 0;
72 5
        $queries = array();
73 5
        while ($row = $res->fetch()) {
74 5
            $val = $row['id'];
75
76 5
            $data = $this->generateFakeData($table);
77
78 5
            if ($pretend === false) {
79 3
                $this->runUpdate($table, $data, "$key = '$val'");
80 3
            }
81
82 5
            ($returnResult === true ? array_push($queries, $this->buildUpdateSQL($table, $data, "$key = '$val'")) : '');
83
84 5
            if (!is_null($callback)) {
85 3
                $callback(++$i);
86 3
            }
87 5
        }
88
89 5
        return $queries;
90
    }
91
92
    /**
93
     * Identify the primary key for a table
94
     *
95
     * @param string $table
96
     *
97
     * @return string Field's name
98
     */
99 13
    protected function getPrimaryKey($table)
100
    {
101
        try {
102 13
            $res = $this->pdo->query("SHOW COLUMNS FROM $table WHERE `Key` = 'Pri'");
103 13
        } catch (\Exception $e) {
104 1
            throw new \PDOException('Query Error : ' . $e->getMessage());
105
        }
106
107 12
        $primary = $res->fetchAll(\PDO::FETCH_COLUMN);
108
        // Didn't find a primary key !
109 12
        if (empty($primary)) {
110 1
            throw new InetAnonException("Can't find a primary key for '$table'");
111
        }
112
113 11
        return $primary[0];
114
    }
115
116
    /**
117
     * Execute the Update with PDO
118
     *
119
     * @param string $table
120
     * @param array  $data
121
     * @param string $where
122
     */
123 3
    private function runUpdate($table, array $data, $where)
124
    {
125 3
        $fields = array();
126 3
        $values = array();
127 3
        foreach ($data as $field => $value) {
128 3
            $fields[] = "$field = IF($field  IS NOT NULL, :$field, NULL)";
129 3
            $values[":$field"] = $value;
130 3
        }
131
132 3
        $sql = "UPDATE $table SET " . implode(', ', $fields) . " WHERE $where";
133 3
        $stmt = $this->pdo->prepare($sql);
134 3
        $stmt->execute($values);
135 3
    }
136
137
    /**
138
     * Execute the Delete with PDO
139
     *
140
     * @param string $table
141
     * @param string $where
142
     */
143 4
    private function runDelete($table, $where, $pretend)
144
    {
145 4
        $where = empty($where) ? '' : " WHERE $where";
146 4
        $sql = "DELETE FROM {$table}{$where}";
147
148 4
        if ($pretend === true) {
149 1
            return $sql;
150
        }
151
152
        try {
153 3
            $res = $this->pdo->query($sql);
0 ignored issues
show
Unused Code introduced by
$res is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
154 3
        } catch (\Exception $e) {
155 1
            throw new \PDOException('Query Error : ' . $e->getMessage());
156
        }
157
158 2
        return $sql;
159
    }
160
161
    /**
162
     * Build the SQL just for debug
163
     *
164
     * @param string $table
165
     * @param array  $data
166
     * @param string $where
167
     *
168
     * @return string
169
     */
170 4
    private function buildUpdateSQL($table, array $data, $where)
171
    {
172 4
        $fieldsVals = array();
173 4
        foreach ($data as $field => $value) {
174 4
            $fieldsVals[] = "$field = IF($field IS NOT NULL, '" . addslashes($value) . "', NULL)";
175 4
        }
176
177 4
        $sql = "UPDATE $table SET " . implode(', ', $fieldsVals) . " WHERE $where";
178
179 4
        return $sql;
180
    }
181
}
182