DeleteAlertCommand::processAlert()   B
last analyzed

Complexity

Conditions 7
Paths 17

Size

Total Lines 55
Code Lines 36

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 36
nc 17
nop 3
dl 0
loc 55
rs 7.8235
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Ps2alerts\Api\Command;
4
5
use Ps2alerts\Api\Command\BaseCommand;
6
use Ps2alerts\Api\Repository\AlertRepository;
7
use Symfony\Component\Console\Command\Command;
8
use Symfony\Component\Console\Input\InputArgument;
9
use Symfony\Component\Console\Input\InputInterface;
10
use Symfony\Component\Console\Output\OutputInterface;
11
12
class DeleteAlertCommand extends BaseCommand
13
{
14
    protected $alertRepo;
15
    protected $verbose = 0;
16
17 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...
18
    {
19
        parent::configure(); // See BaseCommand.php
20
        $this
21
            ->setName('DeleteAlert')
22
            ->setDescription('Deletes an alert and corrects totals')
23
            ->addArgument(
24
                'alert',
25
                InputArgument::REQUIRED,
26
                'Alert ID to process'
27
            );
28
29
        $this->alertRepo = $this->container->get('Ps2alerts\Api\Repository\AlertRepository');
30
    }
31
32
    protected function execute(InputInterface $input, OutputInterface $output)
33
    {
34
        $id = $input->getArgument('alert');
35
36
        $output->writeln("Processing Alert deletion for: {$id}");
37
38
        // If we're requesting a range
39
        if (strpos($id, ',') !== false) {
40
            $split = explode(',', $id);
41
            $ids = range($split[0], $split[1]);
42
            $output->writeln("DELETING ALERTS BETWEEN #{$split[0]} AND #{$split[1]}");
43
44
            foreach ($ids as $id) {
45
                $this->processAlert($id, $output);
46
            }
47
        } else {
48
            $this->processAlert($id, $output);
49
        }
50
    }
51
52
    /**
53
     * Processes an alert
54
     * @param  string          $id
55
     * @param  OutputInterface $output
56
     * @param  boolean         $force
57
     * @return boolean
58
     */
59
    public function processAlert($id, OutputInterface $output, $force = null)
60
    {
61
        $alert = $this->alertRepo->readSingleById($id, 'primary', true);
62
63
        if (empty($force) && empty($alert)) {
64
            $output->writeln("ALERT {$id} DOES NOT EXIST!");
65
            return false;
66
        }
67
68
        $output->writeln("DELETING ALERT {$id}");
69
70
        $players = $this->processPlayers($id);
71
        if ($this->verbose === 1) {
72
            $output->writeln("{$players} players processed");
73
        }
74
75
        $outfits = $this->processOutfits($id);
76
        if ($this->verbose === 1) {
77
            $output->writeln("{$outfits} outfits processed");
78
        }
79
80
        $types = $this->processXP($id);
81
        if ($this->verbose === 1) {
82
            $output->writeln("{$types} XP types processed");
83
        }
84
85
        $tables = [
86
            'ws_classes',
87
            'ws_classes_totals',
88
            'ws_combat_history',
89
            'ws_factions',
90
            'ws_instances',
91
            'ws_map',
92
            'ws_map_initial',
93
            'ws_outfits',
94
            'ws_players',
95
            'ws_pops',
96
            'ws_vehicles',
97
            'ws_vehicles_totals',
98
            'ws_weapons',
99
            'ws_weapons_totals',
100
            'ws_xp'
101
        ];
102
103
        $this->deleteAllFromTables($tables, $id, $output);
104
105
        // Finally delete the alert
106
        $this->deleteAlert($id);
107
108
        if ($this->verbose === 1) {
109
            $output->writeln("Alert {$id} successfully deleted!");
110
        }
111
112
        return true;
113
    }
114
115
    /**
116
     * Processes players for alert
117
     * @param  string $id Alert ID
118
     * @return void
119
     */
120
    protected function processPlayers($id)
121
    {
122
        $cols = [
123
            'playerID',
124
            'playerKills',
125
            'playerDeaths',
126
            'playerTeamKills',
127
            'playerSuicides',
128
            'headshots'
129
        ];
130
131
        $fields = [
132
            'playerKills',
133
            'playerDeaths',
134
            'playerTeamKills',
135
            'playerSuicides',
136
            'headshots'
137
        ];
138
139
        return $this->runProcess(
140
            $id,
141
            $cols,
142
            'ws_players',
143
            'ws_players_total',
144
            'playerID',
145
            $fields
146
        );
147
    }
148
149
    /**
150
     * Processes outfits for alert
151
     * @param  string $id Alert ID
152
     * @return void
153
     */
154
    protected function processOutfits($id)
155
    {
156
        $cols = [
157
            'outfitID',
158
            'outfitKills',
159
            'outfitDeaths',
160
            'outfitTKs',
161
            'outfitSuicides'
162
        ];
163
164
        $fields = [
165
            'outfitKills',
166
            'outfitDeaths',
167
            'outfitTKs',
168
            'outfitSuicides'
169
        ];
170
171
        return $this->runProcess(
172
            $id,
173
            $cols,
174
            'ws_outfits',
175
            'ws_outfits_total',
176
            'outfitID',
177
            $fields
178
        );
179
    }
180
181
    /**
182
     * Processes XPs for alert
183
     * @param  string $id Alert ID
184
     * @return void
185
     */
186
    protected function processXP($id)
187
    {
188
        $cols = [
189
            'SUM(occurances) AS occurances',
190
            'type'
191
        ];
192
193
        $fields = [
194
            'occurances'
195
        ];
196
197
        return $this->runProcess(
198
            $id,
199
            $cols,
200
            'ws_xp',
201
            'ws_xp_totals',
202
            'type',
203
            $fields,
204
            ['type']
205
        );
206
    }
207
208
    /**
209
     * Executes the process based on inputs
210
     * @param  string $id          Alert ID
211
     * @param  array  $cols        Columns to look for
212
     * @param  string $table       Table to look for
213
     * @param  string $totalsTable Table total to update if applicable
214
     * @param  string $filter      Column to filter on
215
     * @param  array  $fields      Fields to summarize
216
     * @param  array  $groupBy     Fields to group by
217
     * @return int
218
     */
219
    protected function runProcess(
220
        $id,
221
        array $cols,
222
        $table,
223
        $totalsTable,
224
        $filter,
225
        array $fields,
226
        $groupBy = null
227
    ) {
228
        // Check each cols to make sure we handle SUM(BLAH) AS BLAH issues
229
230
        foreach ($cols as $key => $col) {
231
            if (strpos($col, 'AS ') !== false) {
232
                $pos = strrpos($col, 'AS ') + 3; # Plus 3 for "AS "
0 ignored issues
show
Unused Code Comprehensibility introduced by
38% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
233
                $len = strlen($col);
234
                $diff = $len - $pos;
235
                $field = substr($col, $pos, $diff);
236
237
                $cols[$key] = $field;
238
            }
239
        }
240
241
        $query = $this->auraFactory->newSelect();
242
        $query->cols($cols);
243
        $query->from($table);
244
        $query->where('resultID = ?', $id);
245
246
        if (!empty($groupBy)) {
247
            $query->groupBy($groupBy);
248
        }
249
250
        $allQuery = $this->db->prepare($query->getStatement());
251
        $allQuery->execute($query->getBindValues());
252
253
        $count = 0;
254
255
        while ($row = $allQuery->fetch(\PDO::FETCH_OBJ)) {
256
            $count++;
257
258
            $update = $this->auraFactory->newUpdate();
259
            $update->table($totalsTable);
260
            $update->where("{$filter} = ?", $row->$filter);
261
262
            foreach ($fields as $field) {
263
                $update->set($field, "{$field} - {$row->$field}");
264
            }
265
266
            $updateQuery = $this->db->prepare($update->getStatement());
267
            $updateQuery->execute($update->getBindValues());
268
        }
269
270
        return $count;
271
    }
272
273
    protected function deleteAllFromTables(array $tables, $id, OutputInterface $output)
274
    {
275
        foreach ($tables as $table) {
276
            $delete = $this->auraFactory->newDelete();
277
            $delete->from($table);
278
            $delete->where('resultID = ?', $id);
279
280
            $deleteQuery = $this->db->prepare($delete->getStatement());
281
            $deleteQuery->execute($delete->getBindValues());
282
283
            $affected = $deleteQuery->rowCount();
284
285
            if ($this->verbose === 1) {
286
                $output->writeln("{$affected} rows deleted from table \"{$table}\"");
287
            }
288
        }
289
    }
290
291
    protected function deleteAlert($id)
292
    {
293
        $delete = $this->auraFactory->newDelete();
294
        $delete->from('ws_results');
295
        $delete->where('ResultID = ?', $id);
296
297
        $deleteQuery = $this->db->prepare($delete->getStatement());
298
        $deleteQuery->execute($delete->getBindValues());
299
    }
300
}
301