forked from webnet-fr/database-anonymizer
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathAnonymizer.php
More file actions
154 lines (130 loc) · 5.78 KB
/
Anonymizer.php
File metadata and controls
154 lines (130 loc) · 5.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
<?php
namespace WebnetFr\DatabaseAnonymizer;
use Doctrine\DBAL\Connection;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
use WebnetFr\DatabaseAnonymizer\Event\AnonymizerEvent;
use WebnetFr\DatabaseAnonymizer\Exception\InvalidAnonymousValueException;
use WebnetFr\DatabaseAnonymizer\Helper\AnonymizerCacheHelper;
/**
* Database anonymizer.
*
* @author Vlad Riabchenko <vriabchenko@webnet.fr>
*/
class Anonymizer
{
private $cacheHelper;
private $dispatcher;
public function __construct(AnonymizerCacheHelper $cacheHelper, ?EventDispatcherInterface $dispatcher = null)
{
$this->cacheHelper = $cacheHelper;
$this->dispatcher = $dispatcher;
}
/**
* Anonymize entire database based on target tables.
*
* @param Connection $connection
* @param TargetTable[] $targets
*
* @throws \Doctrine\DBAL\DBALException
* @throws \Exception
*/
public function anonymize(Connection $connection, array $targets, array $config = [])
{
foreach ($targets as $targetTable) {
if ($targetTable->isTruncate()) {
$dbPlatform = $connection->getDatabasePlatform();
$connection->query('SET FOREIGN_KEY_CHECKS=0');
$truncateQuery = $dbPlatform->getTruncateTableSql($targetTable->getName());
$connection->executeUpdate($truncateQuery);
$connection->query('SET FOREIGN_KEY_CHECKS=1');
} else {
// reset or not the anonymization
$reset = $config['reset'] ?? true;
$numberOfParts = $config['number_of_parts'] ?? 1;
$currentPart = $config['current_part'] ?? 1;
$maximumId = $this->getMaximumId($connection, $targetTable->getName(), $targetTable->getPrimaryKey());
$calculatedPart = $this->splitTable($maximumId, $numberOfParts)[$currentPart - 1];
// $cachedNumberOfParts = $this->cacheHelper->getNumberOfParts($targetTable->getName());
// We reset the lastId on cache
// if ($reset) {
// $this->cacheHelper->reset($targetTable->getName(), $currentPart);
// }
// if (null !== $cachedNumberOfParts && $cachedNumberOfParts !== $numberOfParts) {
// throw new \Exception(
// 'Last ids from cache could not be used as the number of parts are changed.' .
// ' try running with --reset option'
// );
// }
$minimumId = $calculatedPart[0];
$maximumId = $calculatedPart[1];
// if (null !== $lastId = $this->cacheHelper->getLastId($targetTable->getName(), $currentPart)) {
// $minimumId = $lastId;
// }
echo sprintf(">> Anonymizing table %s from id = %d to id = %d%s", $targetTable->getName(),
$minimumId,
$maximumId,
PHP_EOL
);
$allFieldNames = $targetTable->getAllFieldNames();
$pk = $targetTable->getPrimaryKey();
// Select all rows form current table:
// SELECT <all target fields> FROM <target table>
$fetchRowsSQL = $connection->createQueryBuilder()
->select(implode(',', $allFieldNames))
->from($targetTable->getName())
->where(sprintf('%s >= :from_id', $pk[0]))
->andWhere(sprintf('%s <= :to_id', $pk[0]))
->getSQL()
;
$fetchRowsStmt = $connection->prepare($fetchRowsSQL);
$fetchRowsStmt->execute([
'from_id' => $minimumId,
'to_id' => $maximumId,
]);
// Anonymize all rows in current target table.
while ($row = $fetchRowsStmt->fetch()) {
$values = [];
// Anonymize all target fields in current row.
foreach ($targetTable->getTargetFields() as $targetField) {
$anonValue = $targetField->isTruncate()
? null
: $targetField->generate();
// Set anonymized value.
$values[$targetField->getName()] = $anonValue;
}
$pkValues = [];
foreach ($pk as $pkField) {
$pkValues[$pkField] = $row[$pkField];
}
$connection->update($targetTable->getName(), $values, $pkValues);
if ($this->dispatcher) {
$this->dispatcher->dispatch(new AnonymizerEvent($row[$pk[0]], $targetTable->getName(), $values));
}
// $this->cacheHelper->saveLastId($targetTable->getName(), $currentPart, $row['id']);
}
}
}
}
private function getMaximumId(Connection $connection, string $tableName, array $pKey): int
{
$sql = $connection->createQueryBuilder()
->select(sprintf('max(%s) as max_id', $pKey[0]))
->from($tableName)
->getSQL();
$fetchCountStmt = $connection->prepare($sql);
$fetchCountStmt->execute();
return (int) $fetchCountStmt->fetch()['max_id'];
}
private function splitTable(int $maximumId, int $totalParts): array
{
$itemsPerPart = (int) floor($maximumId / $totalParts);
$parts = [[1, $itemsPerPart]];
for ($i=1; $i<$totalParts; $i++) {
$parts[] = [
$parts[$i-1][1] + 1,
min($parts[$i-1][1] + 1 + $itemsPerPart, $maximumId),
];
}
return $parts;
}
}