AlertCombatEndpointController   B
last analyzed

Complexity

Total Complexity 37

Size/Duplication

Total Lines 272
Duplicated Lines 18.01 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 49
loc 272
rs 8.6
c 1
b 0
f 0
wmc 37
lcom 1
cbo 3

5 Methods

Rating   Name   Duplication   Size   Complexity  
F getClassTotals() 49 132 17
A findClassGrouping() 0 14 4
A findClassFaction() 0 14 4
A __construct() 0 7 1
C getCombatTotals() 0 92 11

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
namespace Ps2alerts\Api\Controller\Endpoint\Alerts;
4
5
use Ps2alerts\Api\Exception\InvalidArgumentException;
6
use Ps2alerts\Api\Repository\Metrics\CombatRepository;
7
use Ps2alerts\Api\Repository\Metrics\ClassRepository;
8
use Psr\Http\Message\ServerRequestInterface;
9
use Psr\Http\Message\ResponseInterface;
10
11
class AlertCombatEndpointController extends AlertEndpointController
12
{
13
    public function __construct(
14
        classRepository $classRepository,
15
        combatRepository $combatRepository
16
    ) {
17
        $this->classRepository  = $classRepository;
0 ignored issues
show
Bug introduced by
The property classRepository does not seem to exist. Did you mean repository?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
18
        $this->combatRepository = $combatRepository;
0 ignored issues
show
Bug introduced by
The property combatRepository does not seem to exist. Did you mean repository?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
19
    }
20
21
    /**
22
     * Retrieves combat totals on a global and per-server basis
23
     * @param  ServerRequestInterface $request
24
     * @param  ResponseInterface      $response
25
     * @return ResponseInterface
26
     */
27
    public function getCombatTotals(ServerRequestInterface $request, ResponseInterface $response)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $response is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Coding Style introduced by
getCombatTotals uses the super-global variable $_GET which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
28
    {
29
        try {
30
            $servers = $this->validateQueryStringArguments($_GET['servers'], 'servers');
31
            $zones   = $this->validateQueryStringArguments($_GET['zones'], 'zones');
32
        } catch (InvalidArgumentException $e) {
33
            return $this->respondWithError($e->getMessage(), self::CODE_WRONG_ARGS);
34
        }
35
36
        $serversExploded = explode(',', $servers);
37
        $zonesExploded = explode(',', $zones);
38
        $zonesIn = $this->combatRepository->generateWhereInString($zonesExploded);
0 ignored issues
show
Bug introduced by
The property combatRepository does not seem to exist. Did you mean repository?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
39
40
        $results = [];
41
42
        foreach ($serversExploded as $server) {
43
            $metrics = ['kills', 'deaths', 'teamkills', 'suicides', 'headshots'];
44
            $factions = ['vs', 'nc', 'tr'];
45
46
            // Check if we have an entry in Redis
47
            $data = $this->getRedisUtility()->checkRedis('api', 'combatTotals', "{$server}-data");
48
            $dataArchive = $this->getRedisUtility()->checkRedis('api', 'combatTotals', "{$server}-dataArchive");
49
50
            $mergedArray = [];
51
52
            if (! $data || ! $dataArchive) {
53
                $sums = [];
54
                foreach ($metrics as $metric) {
55
                    foreach ($factions as $faction) {
56
                        $dbMetric = $metric . strtoupper($faction); // e.g. killsVS
57
                        $dataMetric = $metric . strtoupper($faction); // e.g. killsVS
58
59
                        // Handle teamkills inconsistency
60
                        if ($metric === 'teamkills') {
61
                            $dbMetric = 'teamKills' . strtoupper($faction);
62
                        }
63
                        $sums[] = "SUM(factions.{$dbMetric}) AS $dataMetric";
64
                    }
65
66
                    // Totals
67
                    $dbMetric = 'total' . ucfirst($metric); // e.g. killsVS
68
                    $dataMetric = 'total' . ucfirst($metric); // e.g. killsVS
69
70
                    // Handle teamkills inconsistency
71
                    if ($metric === 'teamkills') {
72
                        $dbMetric = 'totalTKs'; // Christ knows why
73
                    }
74
                    $sums[] = "SUM(factions.{$dbMetric}) AS $dataMetric";
75
                }
76
77
                $query = $this->combatRepository->newQuery('single', true);
0 ignored issues
show
Bug introduced by
The property combatRepository does not seem to exist. Did you mean repository?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
78
                $query->cols($sums);
79
                $query->from('ws_factions AS factions');
80
                $query->join(
81
                    'INNER',
82
                    'ws_results AS results',
83
                    "factions.resultID = results.ResultID"
84
                );
85
                $query->where('results.ResultServer = ?', $server);
86
                $query->where("results.ResultAlertCont IN {$zonesIn}");
87
                $query->where('results.Valid = ?', 1);
88
89
                $data = $this->combatRepository->fireStatementAndReturn($query, true);
0 ignored issues
show
Bug introduced by
The property combatRepository does not seem to exist. Did you mean repository?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
90
                $dataArchive = $this->combatRepository->fireStatementAndReturn($query, true, false, true);
0 ignored issues
show
Bug introduced by
The property combatRepository does not seem to exist. Did you mean repository?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
91
92
                // Store the results in Redis
93
                $this->getRedisUtility()->storeInRedis('api', 'combatTotals', "{$server}-data", $data, 3600);
94
                $this->getRedisUtility()->storeInRedis('api', 'combatTotals', "{$server}-dataArchive", $dataArchive, 3600);
95
            }
96
97
            $metrics = ['kills', 'deaths', 'teamkills', 'suicides', 'headshots'];
98
            $factions = ['vs', 'nc', 'tr'];
99
100
            // Merge the two arrays together
101
            foreach ($metrics as $metric) {
102
                // Tot up totals
103
                $dbMetric = 'total' . ucfirst($metric);
104
                $mergedArray['totals'][$metric] = (int) $data[$dbMetric] + (int) $dataArchive[$dbMetric];
105
                $results['all']['totals'][$metric] += $mergedArray['totals'][$metric];
106
107
                foreach ($factions as $faction) {
108
                    $dbMetric = $metric . strtoupper($faction);
109
                    $mergedArray[$metric][$faction] = (int) $data[$dbMetric] + (int) $dataArchive[$dbMetric];
110
                    $results['all'][$metric][$faction] += $mergedArray[$metric][$faction];
111
                }
112
            }
113
114
            $results[$server] = $mergedArray;
115
        }
116
117
        return $this->respondWithData($results);
118
    }
119
120
    public function getClassTotals(ServerRequestInterface $request, ResponseInterface $response)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $response is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Coding Style introduced by
getClassTotals uses the super-global variable $_GET which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
121
    {
122
        try {
123
            $servers = $this->validateQueryStringArguments($_GET['servers'], 'servers');
124
            $zones   = $this->validateQueryStringArguments($_GET['zones'], 'zones');
125
        } catch (InvalidArgumentException $e) {
126
            return $this->respondWithError($e->getMessage(), self::CODE_WRONG_ARGS);
127
        }
128
129
        $serversExploded = explode(',', $servers);
130
        $zonesExploded = explode(',', $zones);
131
        $zonesIn = $this->combatRepository->generateWhereInString($zonesExploded);
0 ignored issues
show
Bug introduced by
The property combatRepository does not seem to exist. Did you mean repository?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
132
        $classes = $this->getConfig()['classes'];
133
134
        // Build classes array
135
        foreach ($classes as $class) {
136
            $results['totals'][$class] = [
0 ignored issues
show
Coding Style Comprehensibility introduced by
$results was never initialized. Although not strictly required by PHP, it is generally a good practice to add $results = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
137
                'kills'     => 0,
138
                'deaths'    => 0,
139
                'teamkills' => 0,
140
                'suicides'  => 0,
141
                'kdr'       => 0
142
            ];
143
        }
144
145
        foreach ($serversExploded as $server) {
146
            // Check if we have an entry in Redis
147
            $data = $this->getRedisUtility()->checkRedis('api', 'classCombat', "{$server}-data", 'object');
148
            $dataArchive = $this->getRedisUtility()->checkRedis('api', 'classCombat', "{$server}-dataArchive", 'object');
149
150
            // If data needs a pull
151
            if (! $data || ! $dataArchive) {
152
                $query = $this->combatRepository->newQuery('single', true);
0 ignored issues
show
Bug introduced by
The property combatRepository does not seem to exist. Did you mean repository?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
153
                $query->cols([
154
                        'classID',
155
                        'results.ResultServer AS server',
156
                        'SUM(kills) AS kills',
157
                        'SUM(deaths) AS deaths',
158
                        'SUM(teamkills) AS teamkills',
159
                        'SUM(suicides) AS suicides'
160
                ]);
161
                $query->from('ws_classes AS classes');
162
                $query->join(
163
                    'INNER',
164
                    'ws_results AS results',
165
                    "classes.resultID = results.ResultID"
166
                );
167
                $query->where('results.ResultServer = ?', $server);
168
                $query->where("results.ResultAlertCont IN {$zonesIn}");
169
                $query->where('results.Valid = ?', 1);
170
                $query->where('classID != ?', 0);
171
                $query->groupBy(['classID, server']);
172
173
                $data = $this->classRepository->fireStatementAndReturn($query, false, true);
0 ignored issues
show
Bug introduced by
The property classRepository does not seem to exist. Did you mean repository?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
174
                $dataArchive = $this->classRepository->fireStatementAndReturn($query, false, true, true);
0 ignored issues
show
Bug introduced by
The property classRepository does not seem to exist. Did you mean repository?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
175
176
                // Store the results in Redis
177
                $this->getRedisUtility()->storeInRedis('api', 'classCombat', "{$server}-data", $data, 3600);
178
                $this->getRedisUtility()->storeInRedis('api', 'classCombat', "{$server}-dataArchive", $dataArchive, 3600);
179
            }
180
181
            // Typecase into ints and increase totals
182
            $metrics = ['kills', 'deaths', 'teamkills', 'suicides'];
183 View Code Duplication
            foreach ($data as $row) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
184
                $row->classID   = (int) $row->classID;
185
                $row->server   = (int) $row->server;
186
                $classGroup = $this->findClassGrouping($row->classID);
187
                $faction = $this->findClassFaction($row->classID);
188
189
                foreach ($metrics as $metric) {
190
                    $row->$metric = (int) $row->$metric;
191
                    $results[$row->server][$row->classID][$metric] += $row->$metric;
0 ignored issues
show
Bug introduced by
The variable $results does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
192
                    $results['totals'][$row->classID][$metric] += $row->$metric;
193
                    $results['byMetric'][$metric][$row->classID] += $row->$metric;
194
                    $results['byMetric'][$metric]['total'] += $row->$metric;
195
196
                    // Assign to class group
197
                    $results['classGroups']['totals'][$classGroup][$metric] += $row->$metric;
198
                    $results['classGroups'][$row->server][$classGroup][$metric] += $row->$metric;
199
                    $results['classGroupFactionMetric'][$classGroup][$faction][$metric] += $row->$metric;
200
                }
201
            }
202
203 View Code Duplication
            foreach ($dataArchive as $row) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
204
                $row->classID   = (int) $row->classID;
205
                $row->server   = (int) $row->server;
206
207
                foreach ($metrics as $metric) {
208
                    $row->$metric = (int) $row->$metric;
209
                    $results[$row->server][$row->classID][$metric] += $row->$metric;
210
                    $results['totals'][$row->classID][$metric] += $row->$metric;
211
                    $results['byMetric'][$metric][$row->classID] += $row->$metric;
212
                    $results['byMetric'][$metric]['total'] += $row->$metric;
213
214
                    // Assign to class group
215
                    $classGroup = $this->findClassGrouping($row->classID);
216
                    $results['classGroups']['totals'][$classGroup][$metric] += $row->$metric;
217
                    $results['classGroups'][$row->server][$classGroup][$metric] += $row->$metric;
218
219
                    $faction = $this->findClassFaction($row->classID);
220
                    $results['classGroupFactionMetric'][$classGroup][$faction][$metric] += $row->$metric;
221
                }
222
            }
223
224
            // Calculate KDRs
225
            foreach ($results['byMetric']['kills'] as $class => $kills) {
226
                $results['byMetric']['kdr'][$class] = $kills / $results['byMetric']['deaths'][$class];
227
228
                if (empty($results['byMetric']['kdr']['max'])) {
229
                    $results['byMetric']['kdr']['max'] = $results['byMetric']['kdr'][$class];
230
                }
231
232
                if ($results['byMetric']['kdr'][$class] > $results['byMetric']['kdr']['max']) {
233
                    $results['byMetric']['kdr']['max'] = $results['byMetric']['kdr'][$class];
234
                }
235
            }
236
237 View Code Duplication
            foreach ($results['classGroups'] as $server => $classArray) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
238
                foreach ($classArray as $class => $metrics) {
239
                    $results['classGroups'][$server][$class]['kdr'] = $metrics['kills'] / $metrics['deaths'];
240
                }
241
            }
242
243 View Code Duplication
            foreach ($results['classGroupFactionMetric'] as $class => $factions) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
244
                foreach ($factions as $faction => $metrics) {
245
                    $results['classGroupFactionMetric'][$class][$faction]['kdr'] = $metrics['kills'] / $metrics['deaths'];
246
                }
247
            }
248
        }
249
250
        return $this->respondWithData($results);
251
    }
252
253
    private function findClassGrouping($classID)
254
    {
255
        $classGroups = $this->getConfig()['classesGroups'];
256
257
        foreach ($classGroups as $group => $ids) {
258
            foreach ($ids as $id) {
259
                if ($classID === $id) {
260
                    return $group;
261
                }
262
            }
263
        }
264
265
        return false;
266
    }
267
268
    private function findClassFaction($classID)
269
    {
270
        $classesFactions = $this->getConfig()['classesFactions'];
271
272
        foreach ($classesFactions as $faction => $ids) {
273
            foreach ($ids as $id) {
274
                if ($classID === $id) {
275
                    return $faction;
276
                }
277
            }
278
        }
279
280
        return false;
281
    }
282
}
283