Completed
Push — feature/servers-redesign ( 2ca029...06aadf )
by Vladimir
03:58
created

MatchServerRelationship::down()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 5
nc 1
nop 0
1
<?php
2
3
use BZIon\Phinx\KernelReadyMigration;
4
5
class MatchServerRelationship extends KernelReadyMigration
6
{
7
    public function up()
8
    {
9
        $matches = $this->table(Match::TABLE);
10
        $matches
11
            ->addColumn('server_id', 'integer', [
12
                'after'   => 'match_details',
13
                'limit'   => 10,
14
                'signed'  => false,
15
                'null'    => true,
16
                'comment' => 'The server where this match took place'
17
            ])
18
            ->addForeignKey('server_id', 'servers', 'id', ['delete' => 'CASCADE'])
19
            ->save()
20
        ;
21
22
        // Build a cache for server addresses
23
        $address = [];
24
        $servers = Server::getQueryBuilder()->getModels($fast = true);
25
26
        /** @var Server $server */
27
        foreach ($servers as $server) {
28
            $address[sprintf('%s:%s', $server->getDomain(), $server->getPort())] = $server->getId();
29
        }
30
31
        // Get all of the matches we can work with
32
        $matchQB = new MatchQueryBuilder('Match', [
33
            'columns' => [
34
                'server' => 'server',
35
            ]
36
        ]);
37
        $query = $matchQB
38
            ->where('server')->isNotNull()
39
            ->where('server')->notEquals('')
40
            ->limit(1000);
41
42
        $pageCount = $query->countPages();
43
44
        for ($i = 1; $i <= $pageCount; $i++) {
45
            $matches = $query
46
                ->fromPage($i)
47
                ->getModels($fast = true)
48
            ;
49
50
            /** @var Match $match */
51
            foreach ($matches as $match) {
52
                $match_address = $match->getServerAddress();
53
54
                if (isset($address[$match_address])) {
55
                    $match->setServer($address[$match_address]);
56
                }
57
            }
58
        }
59
    }
60
61
    public function down()
62
    {
63
        $matches = $this->table(Match::TABLE);
64
        $matches
65
            ->dropForeignKey('server_id')
66
            ->removeColumn('server_id')
67
        ;
68
    }
69
}
70