Completed
Push — master ( 8ae23c...e67dbb )
by Matthew
09:17
created

AlertStatisticsLoader::readTotals()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 23
Code Lines 13

Duplication

Lines 23
Ratio 100 %

Importance

Changes 9
Bugs 0 Features 5
Metric Value
c 9
b 0
f 5
dl 23
loc 23
rs 9.0857
cc 2
eloc 13
nc 2
nop 0
1
<?php
2
3
namespace Ps2alerts\Api\Loader\Statistics;
4
5
use Ps2alerts\Api\Loader\Statistics\AbstractStatisticsLoader;
6
use Ps2alerts\Api\QueryObjects\QueryObject;
7
use Ps2alerts\Api\Repository\AlertRepository;
8
use Ps2alerts\Api\Loader\Metrics\MapMetricsLoader;
9
use Ps2alerts\Api\Validator\AlertInputValidator;
10
use Ps2alerts\Api\Helper\DataFormatterHelper;
11
12
class AlertStatisticsLoader extends AbstractStatisticsLoader
13
{
14
    /**
15
     * @var \Ps2alerts\Api\Repository\AlertRepository
16
     */
17
    protected $repository;
18
19
    /**
20
     * @var \Ps2alerts\Api\Loader\Metrics\MapMetricsLoader
21
     */
22
    protected $mapLoader;
23
24
    /**
25
     * @var \Ps2alerts\Api\Helper\DataFormatterHelper
26
     */
27
    protected $dataFormatter;
28
29
    /**
30
     * Construct
31
     *
32
     * @param \Ps2alerts\Api\Repository\AlertRepository       $repository
33
     * @param \Ps2alerts\Api\Loader\Metrics\MapMetricsLoader  $mapLoader
34
     * @param \Ps2alerts\Api\Helper\DataFormatter             $dataFormatter
35
     */
36
    public function __construct(
37
        AlertRepository     $repository,
38
        MapMetricsLoader    $mapLoader,
39
        DataFormatterHelper $dataFormatter
40
    ) {
41
        $this->repository    = $repository;
42
        $this->mapLoader     = $mapLoader;
43
        $this->dataFormatter = $dataFormatter;
44
45
        $this->setCacheNamespace('Statistics');
46
        $this->setType('Alerts');
47
    }
48
49
    /**
50
     * Read total counts for alerts
51
     *
52
     * @param  array $post
0 ignored issues
show
Bug introduced by
There is no parameter named $post. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
53
     *
54
     * @return array
55
     */
56 View Code Duplication
    public function readTotals()
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...
57
    {
58
        $redisKey = "{$this->getCacheNamespace()}:{$this->getType()}:Totals";
59
        $post     = $this->processPost();
60
61
        $redisKey = $this->appendRedisKey($post, $redisKey);
62
63
        if ($this->checkRedis($redisKey)) {
64
            return $this->getFromRedis($redisKey);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->getFromRedis($redisKey); (string) is incompatible with the return type documented by Ps2alerts\Api\Loader\Sta...sticsLoader::readTotals of type array.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

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

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
65
        }
66
67
        $queryObject = new QueryObject;
68
        $queryObject = $this->setupQueryObject($queryObject, $post);
69
70
        $queryObject->addSelect('COUNT(ResultID) AS COUNT');
71
72
        $this->setCacheExpireTime(900); // 15 mins
73
74
        return $this->cacheAndReturn(
75
            $this->repository->read($queryObject),
76
            $redisKey
77
        );
78
    }
79
80
    /**
81
     * Retrieves all zone totals and caches as required
82
     *
83
     * @return array
84
     */
85
    public function readZoneTotals()
86
    {
87
        $masterRedisKey = "{$this->getCacheNamespace()}:{$this->getType()}:Totals:Zones";
88
89
        if ($this->checkRedis($masterRedisKey)) {
90
            return $this->getFromRedis($masterRedisKey);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->getFromRedis($masterRedisKey); (string) is incompatible with the return type documented by Ps2alerts\Api\Loader\Sta...sLoader::readZoneTotals of type array.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

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

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
91
        }
92
93
        $servers  = [1,10,13,17,25,1000,2000];
94
        $zones    = [2,4,6,8];
95
        $factions = ['vs','nc','tr','draw'];
96
97
        $results = [];
98
        $this->setCacheExpireTime(3600); // 1 Hour
99
100
        // Dat loop yo
101
        foreach ($servers as $server) {
102
            foreach ($zones as $zone) {
103
                foreach ($factions as $faction) {
104
                    $results[$server][$zone][$faction] = $this->getZoneStats($server, $zone, $faction);
105
                }
106
            }
107
        }
108
109
        // Commit to Redis
110
        return $this->cacheAndReturn(
111
            $results,
112
            $masterRedisKey
113
        );
114
    }
115
116
    /**
117
     * Gets all information regarding zone victories out of the DB and caches as
118
     * required
119
     *
120
     * @see readZoneTotals()
121
     *
122
     * @param  integer $server
123
     * @param  integer $zone
124
     * @param  integer $faction
125
     *
126
     * @return array
127
     */
128
    public function getZoneStats($server, $zone, $faction)
129
    {
130
        $redisKey = "{$this->getCacheNamespace()}:{$this->getType()}:Totals:Zones";
131
        $redisKey .= ":{$server}:{$zone}:{$faction}";
132
133
        if ($this->checkRedis($redisKey)) {
134
            return $this->getFromRedis($redisKey);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->getFromRedis($redisKey); (string) is incompatible with the return type documented by Ps2alerts\Api\Loader\Sta...icsLoader::getZoneStats of type array.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

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

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
135
        }
136
137
        // Fire a set of queries to build the object required
138
        $queryObject = new QueryObject;
139
        $queryObject->addSelect('COUNT(ResultID) AS COUNT');
140
        $queryObject->addWhere([
141
            'col'   => 'ResultServer',
142
            'value' => $server
143
        ]);
144
        $queryObject->addWhere([
145
            'col'   => 'ResultAlertCont',
146
            'value' => $zone
147
        ]);
148
        $queryObject->addWhere([
149
            'col'   => 'ResultWinner',
150
            'value' => $faction
151
        ]);
152
153
        // Commit to Redis
154
        return $this->cacheAndReturn(
155
            $this->repository->read($queryObject)[0]["COUNT"],
156
            $redisKey
157
        );
158
    }
159
160
    /**
161
     * Generates the data required for History Summaries
162
     *
163
     * @param  array $post
164
     *
165
     * @return array
166
     */
167
    public function readHistorySummary(array $post)
168
    {
169
        $redisKey = "{$this->getCacheNamespace()}:{$this->getType()}:HistorySummary";
170
        $redisKey = $this->appendRedisKey($post, $redisKey);
171
        $post     = $this->processPostVars($post);
0 ignored issues
show
Bug introduced by
The method processPostVars() does not exist on Ps2alerts\Api\Loader\Sta...s\AlertStatisticsLoader. Did you maybe mean processPost()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
172
173
        $queryObject = new QueryObject;
174
        $queryObject = $this->setupQueryObject($queryObject, $post);
175
        $queryObject->addSelect('FROM_UNIXTIME(ResultEndTime) AS ResultEndTime');
176
        $queryObject->addSelect('ResultWinner');
177
        $queryObject->addWhere([
178
            'col'   => 'InProgress',
179
            'value' => 0
180
        ]);
181
        $queryObject->setLimit('unlimited');
182
183
        $minDate = '2014-10-29'; // Beginning of tracking
184
        $maxDate = date('Y-m-d'); // Today unless set
185
186
        // If there is a minimum date set
187 View Code Duplication
        if (! empty($post['wheres']['morethan']['ResultEndTime'])) {
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...
188
            if (is_integer($post['wheres']['morethan']['ResultEndTime'])) {
189
                $minDate = date('Y-m-d', $post['wheres']['morethan']['ResultEndTime']);
190
            } else {
191
                $minDate = date('Y-m-d', strtotime($post['wheres']['morethan']['ResultEndTime']));
192
            }
193
        }
194
195
        // If there is a maximum date set
196 View Code Duplication
        if (! empty($post['wheres']['lessthan']['ResultEndTime'])) {
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...
197
            if (is_integer($post['wheres']['lessthan']['ResultEndTime'])) {
198
                $maxDate = date('Y-m-d', $post['wheres']['lessthan']['ResultEndTime']);
199
            } else {
200
                $maxDate = date('Y-m-d', strtotime($post['wheres']['lessthan']['ResultEndTime']));
201
            }
202
        }
203
204
        $redisKey .= "/min-{$minDate}/max-{$maxDate}";
205
206
        if ($this->checkRedis($redisKey)) {
207
            return $this->getFromRedis($redisKey);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->getFromRedis($redisKey); (string) is incompatible with the return type documented by Ps2alerts\Api\Loader\Sta...der::readHistorySummary of type array.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

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

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
208
        }
209
210
        // Get the data to parse
211
        $alerts = $this->repository->read($queryObject);
212
213
        // Generate the range of dates
214
        $dates = $this->dataFormatter->createDateRangeArray($minDate, $maxDate);
215
        $dateRange = [];
216
217
        // Generates the victory totals for each date
218
        foreach ($dates as $date) {
219
            $dateRange[$date] = [
220
                'vs'   => 0,
221
                'nc'   => 0,
222
                'tr'   => 0,
223
                'draw' => 0
224
            ];
225
        }
226
227
        // Calculate metrics
228
        foreach ($alerts as $alert) {
229
            $date = date('Y-m-d', strtotime($alert['ResultEndTime']));
230
            $winner = strtolower($alert['ResultWinner']);
231
232
            $dateRange[$date][$winner]++;
233
        }
234
235
        // Commit to Redis
236
        return $this->cacheAndReturn(
237
            $dateRange,
238
            $redisKey
239
        );
240
    }
241
242
    /**
243
     * Reds the alert history based off two dates and other filters
244
     *
245
     * @param  array  $post [description]
246
     *
247
     * @return array
248
     */
249
    public function readAlertHistory(array $post)
250
    {
251
        $minDate = date('U', strtotime("-24 hours"));
252
        $maxDate = date('U');
253
254
        if (! empty($post['minDate'])) {
255
            $minDate = date('U', $post['minDate']);
256
        }
257
258
        if (! empty($post['maxDate'])) {
259
            $maxDate = date('U', $post['maxDate']);
260
        }
261
262
        $queryObject = new QueryObject;
263
        $queryObject->addWhere([
264
            'col'   => 'ResultEndTime',
265
            'op'    => '>',
266
            'value' => $minDate
267
        ]);
268
        $queryObject->addWhere([
269
            'col'   => 'ResultEndTime',
270
            'op'    => '<',
271
            'value' => $maxDate
272
        ]);
273
274 View Code Duplication
        if (! empty($post['server'])) {
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...
275
            $queryObject->addWhere([
276
                'col'   => 'ResultServer',
277
                'value' => $post['server']
278
            ]);
279
        }
280
281
        if (! empty($post['faction'])) {
282
            $queryObject->addWhere([
283
                'col'   => 'ResultWinner',
284
                'value' => $post['faction']
285
            ]);
286
        }
287
288
        // Enforce a limit of 50 returns to prevent overload
289
        $queryObject->setLimit(50);
290
        $queryObject->setOrderBy('result');
291
        $queryObject->setOrderByDirection('desc');
292
293
        if (! empty($post['orderBy'])) {
294
            if ($post['orderBy'] === 'asc' || $post['orderBy'] === 'desc') {
295
                $queryObject->setOrderByDirection($post['orderBy']);
296
            }
297
        }
298
299
        $alerts = $this->repository->read($queryObject);
300
301
        // Grab the map information for each alert returned
302
        foreach ($alerts as $key => $alert) {
303
            $alertKey = "Alert:{$alert['ResultID']}";
304
305
            // Cache the alert if it's not been seen before
306
            if ($this->checkRedis($alertKey) === false) {
307
                $this->cacheAndReturn($alert, $alertKey);
308
            }
309
310
            // Cache the map result so we don't have to get it every time and set
311
            $alerts[$key]['map'] = $this->mapLoader->readLatest($alert['ResultID']);
312
        }
313
314
        return $this->cacheAndReturn($alerts);
315
    }
316
}
317