LeaderboardPlayersCommand::execute()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 6

Duplication

Lines 10
Ratio 100 %

Importance

Changes 0
Metric Value
cc 1
eloc 6
nc 1
nop 2
dl 10
loc 10
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace Ps2alerts\Api\Command;
4
5
use Ps2alerts\Api\Command\BaseCommand;
6
use Symfony\Component\Console\Input\InputArgument;
7
use Symfony\Component\Console\Input\InputInterface;
8
use Symfony\Component\Console\Output\OutputInterface;
9
10
class LeaderboardPlayersCommand extends BaseCommand
11
{
12
    protected $redis;
13
14 View Code Duplication
    protected function configure()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
15
    {
16
        parent::configure(); // See BaseCommand.php
17
        $this
18
            ->setName('Leaderboards:Players')
19
            ->setDescription('Processes player leaderboards')
20
            ->addArgument(
21
                'server',
22
                InputArgument::REQUIRED
23
            );
24
25
        $this->redis = $this->container->get('redis');
26
    }
27
28 View Code Duplication
    protected function execute(InputInterface $input, OutputInterface $output)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
29
    {
30
        $start = microtime(true);
31
        $output->writeln("Running Player Leaderboards");
32
33
        $this->playerLeaderboards($input, $output);
34
35
        $end = microtime(true);
36
        $output->writeln("Processing took ".gmdate("H:i:s", ($end - $start)));
37
    }
38
39
    public function playerLeaderboards(InputInterface $input, OutputInterface $output)
40
    {
41
        $metrics = [
42
            'playerKills',
43
            'playerDeaths',
44
            'playerTeamkills',
45
            'playerSuicides',
46
            'headshots'
47
        ];
48
        $serverArg = $input->getArgument('server');
49
50
        // Allows server 0, meaning all servers but not to process every server
51
        if ($serverArg === 'all') {
52
            $servers = [0, 1, 10, 13, 17, 25, 1000, 2000];
53
        } else {
54
            $servers = [$serverArg];
55
        }
56
57
        foreach ($servers as $server) {
58
            foreach ($metrics as $metric) {
59
                $this->markAsBeingUpdated($metric, $server);
60
            }
61
        }
62
63
        foreach ($servers as $server) {
64
            foreach ($metrics as $metric) {
65
                $count = 0;
66
                $limit = 10000;
67
                $ladderLimit = 10000;
68
                $pos = 1;
69
70
                $output->writeln("Running metric: {$metric} for server {$server}");
71
72
                $idList = "ps2alerts:api:leaderboards:players:{$metric}:listById-{$server}";
73
                $nameList = "ps2alerts:api:leaderboards:players:{$metric}:listByName-{$server}";
74
75
                // Delete the lists for reprocessing
76
                if ($this->redis->exists($idList)) {
77
                    $this->redis->del($idList);
78
                }
79
                if ($this->redis->exists($nameList)) {
80
                    $this->redis->del($nameList);
81
                }
82
83
                // Continue with loop until we don't have a count % modulus returning from the query
84
                while ($count < $ladderLimit && $count % $limit === 0 || $count === 0) {
85
                    $per = ($count / $ladderLimit) * 100;
86
                    $output->writeln("========= {$count} / {$ladderLimit} ({$per}%) =========");
87
88
                    $query = $this->auraFactory->newSelect();
89
                    $query->cols(['*']);
90
                    $query->from('ws_players_total');
91
                    if ($server != 0) {
92
                         $query->where("playerServer = ?", $server);
93
                    }
94
                    $query->orderBy([$metric.' DESC']);
95
                    $query->limit($limit);
96
                    $query->offset($count);
97
98
                    $statement = $this->db->prepare($query->getStatement());
99
                    $statement->execute($query->getBindValues());
100
101
                    $count = $count + $statement->rowCount();
102
103
                    $output->writeln('Processing records...');
104
105
                    while ($player = $statement->fetch(\PDO::FETCH_OBJ)) {
106
                        $playerPosKey = "ps2alerts:api:leaderboards:players:pos:{$player->playerID}";
107
108
                        // If player record doesn't exist
109
                        if (!$this->redis->exists($playerPosKey)) {
110
                            $data = [
111
                                'updated' => [
112
                                    'daily'   => date('U'),
113
                                    'weekly'  => date('U'),
114
                                    'monthly' => date('U'),
115
                                ]
116
                            ];
117
                        } else {
118
                            $data = json_decode($this->redis->get($playerPosKey), true);
119
                        }
120
121
                        $deadlines = [
122
                            'daily',
123
                            'weekly',
124
                            'monthly'
125
                        ];
126
127
                        foreach ($deadlines as $deadline) {
128
                            // Create the array if empty
129
                            if (empty($data[$server][$metric][$deadline])) {
130
                                $data[$server][$metric][$deadline] = [];
131
                            }
132
133
                            $row = $data[$server][$metric][$deadline];
134
                            // If new record for the metric
135
                            if (empty($row)) {
136
                                $row['old']['pos'] = 0;
137
                                $row['old']['val'] = 0;
138
                                $row['new']['pos'] = 0;
139
                                $row['new']['val'] = 0;
140
                            }
141
142
                            // Flip new to old
143
                            if (!empty($row)) {
144
                                $row['old']['pos'] = $row['new']['pos'];
145
                                $row['old']['val'] = $row['new']['val'];
146
                            }
147
148
                            $dateObj  = new \DateTime('now');
149
                            $interval = 'PT0H'; // Default to now.
150
151
                            if ($deadline === 'weekly') {
152
                                $interval = 'P7D';
153
                            } else if ($deadline === 'monthly') {
154
                                $interval = 'P1M';
155
                            }
156
157
                            $dateObj->sub(new \DateInterval($interval));
158
                            $deadlineTime = $dateObj->format('U');
159
160
                            if ($data['updated'][$deadline] <= $deadlineTime) {
161
                                // Update with new data
162
                                $col = $metric;
163
                                if ($metric === 'playerTeamkills') {
164
                                    $col = 'playerTeamKills'; #fml
165
                                }
166
167
                                $row['new']['pos'] = $pos;
168
                                $row['new']['val'] = (int) $player->$col;
169
                                $data['updated'][$deadline] = date('U');
170
171
                                $data[$server][$metric][$deadline] = $row; // Replace
172
173
                                $this->redis->set($playerPosKey, json_encode($data));
174
                            }
175
                        }
176
177
                        $this->redis->rpush($idList, $player->playerID);
178
                        $this->redis->rpush($nameList, $player->playerName);
179
                        $pos++;
180
                    }
181
                }
182
183
                $this->markMetricAsComplete($metric, $server);
184
            }
185
            $this->markAsComplete($server);
186
        }
187
    }
188
189
    public function markAsBeingUpdated($metric, $server)
190
    {
191
        $key = "ps2alerts:api:leaderboards:status:{$server}";
192
193
        // Create the key if it doesn't exist for some reason (1st runs)
194
        if (!$this->redis->exists($key)) {
195
            $data = [
196
                'beingUpdated' => 1,
197
                'lastUpdated'  => date('U'),
198
                $metric        => date('U'),
199
            ];
200
        } else {
201
            $data = json_decode($this->redis->get($key), true);
202
            $data['beingUpdated'] = 1;
203
            $data[$metric]        = date('U');
204
        }
205
206
        $this->redis->set($key, json_encode($data));
207
    }
208
209
    public function markMetricAsComplete($metric, $server)
210
    {
211
        $key = "ps2alerts:api:leaderboards:status:{$server}";
212
213
        $data = json_decode($this->redis->get($key), true);
214
        $data[$metric] = date('U');
215
        $this->redis->set($key, json_encode($data));
216
    }
217
218
    public function markAsComplete($server)
219
    {
220
        $key = "ps2alerts:api:leaderboards:status:{$server}";
221
222
        $data = json_decode($this->redis->get($key), true);
223
224
        $data['beingUpdated'] = 0;
225
        $data['lastUpdated'] = date('U');
226
        $this->redis->set($key, json_encode($data));
227
    }
228
}
229