Completed
Push — master ( c32e20...5b9784 )
by Alejandro
15s
created

Version20180913205455::determineAddress()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
nc 3
nop 1
dl 0
loc 12
rs 9.8666
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
namespace ShlinkMigrations;
5
6
use Doctrine\DBAL\DBALException;
7
use Doctrine\DBAL\Schema\Schema;
8
use Doctrine\Migrations\AbstractMigration;
9
use Shlinkio\Shlink\Common\Exception\WrongIpException;
10
use Shlinkio\Shlink\Common\Util\IpAddress;
11
12
/**
13
 * Auto-generated Migration: Please modify to your needs!
14
 */
15
final class Version20180913205455 extends AbstractMigration
16
{
17
    /**
18
     * @param Schema $schema
19
     */
20
    public function up(Schema $schema): void
21
    {
22
        // Nothing to create
23
    }
24
25
    /**
26
     * @param Schema $schema
27
     * @throws DBALException
28
     */
29
    public function postUp(Schema $schema): void
30
    {
31
        $qb = $this->connection->createQueryBuilder();
32
        $qb->select('id', 'remote_addr')
33
           ->from('visits');
34
        $st = $this->connection->executeQuery($qb->getSQL());
35
36
        $qb = $this->connection->createQueryBuilder();
37
        $qb->update('visits', 'v')
38
           ->set('v.remote_addr', ':obfuscatedAddr')
39
           ->where('v.id=:id');
40
41
        while ($row = $st->fetch(\PDO::FETCH_ASSOC)) {
42
            $addr = $row['remote_addr'] ?? null;
43
            if ($addr === null) {
44
                continue;
45
            }
46
47
            $qb->setParameters([
48
                'id' => $row['id'],
49
                'obfuscatedAddr' => $this->determineAddress((string) $addr),
50
            ])->execute();
51
        }
52
    }
53
54
    private function determineAddress(string $addr): ?string
55
    {
56
        if ($addr === IpAddress::LOCALHOST) {
57
            return $addr;
58
        }
59
60
        try {
61
            return (string) IpAddress::fromString($addr)->getObfuscatedCopy();
62
        } catch (WrongIpException $e) {
63
            return null;
64
        }
65
    }
66
67
    /**
68
     * @param Schema $schema
69
     */
70
    public function down(Schema $schema): void
71
    {
72
        // Nothing to rollback
73
    }
74
}
75