Passed
Push — master ( 791672...96c1a3 )
by Webnet
01:40
created

Anonymizer::anonymize()   B

Complexity

Conditions 7
Paths 7

Size

Total Lines 36
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 20
nc 7
nop 2
dl 0
loc 36
rs 8.6666
c 0
b 0
f 0
1
<?php
2
3
namespace WebnetFr\DatabaseAnonymizer;
4
5
use Doctrine\DBAL\Connection;
6
use WebnetFr\DatabaseAnonymizer\Exception\InvalidAnonymousValueException;
7
8
/**
9
 * Database anonymizer.
10
 *
11
 * @author Vlad Riabchenko <[email protected]>
12
 */
13
class Anonymizer
14
{
15
    /**
16
     * Anonymize entire database based on target tables.
17
     *
18
     * @param Connection $connection
19
     * @param TargetTable[] $targets
20
     */
21
    public function anonymize(Connection $connection, array $targets)
22
    {
23
        foreach ($targets as $targetTable) {
24
            $allFieldNames = $targetTable->getAllFieldNames();
25
            $pk = $targetTable->getPrimaryKey();
26
27
            // Select all rows form current table:
28
            // SELECT <all target fields> FROM <target table>
29
            $fetchRowsSQL = $connection->createQueryBuilder()
30
                ->select(join(',', $allFieldNames))
31
                ->from($targetTable->getName())
32
                ->getSQL();
33
            $fetchRowsStmt = $connection->prepare($fetchRowsSQL);
34
            $fetchRowsStmt->execute();
35
36
            // Anonymize all rows in current target table.
37
            while ($row = $fetchRowsStmt->fetch()) {
38
                $values = [];
39
                // Anonymize all target fields in current row.
40
                foreach ($targetTable->getTargetFields() as $targetField) {
41
                    $anonValue = $targetField->generate();
42
43
                    if (!is_null($anonValue) && !is_string($anonValue)) {
44
                        throw new InvalidAnonymousValueException('Generated value must be null or string');
45
                    }
46
47
                    // Set anonymized value.
48
                    $values[$targetField->getName()] =  $anonValue;
49
                }
50
51
                $pkValues = [];
52
                foreach ($pk as $pkField) {
53
                    $pkValues[$pkField] = $row[$pkField];
54
                }
55
56
                $connection->update($targetTable->getName(), $values, $pkValues);
57
            }
58
        }
59
    }
60
}
61