Completed
Push — master ( 189bb6...0d32b3 )
by Matthew
03:08
created

AbstractStatisticsLoader   B

Complexity

Total Complexity 36

Size/Duplication

Total Lines 222
Duplicated Lines 13.51 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 15
Bugs 2 Features 6
Metric Value
c 15
b 2
f 6
dl 30
loc 222
wmc 36
lcom 1
cbo 3
rs 8.8

6 Methods

Rating   Name   Duplication   Size   Complexity  
A setFlags() 0 4 1
A getFlags() 0 4 1
A readStatistics() 0 18 2
D appendRedisKey() 9 37 9
C processPostVars() 3 27 7
C setupQueryObject() 18 71 16

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\Loader\Statistics;
4
5
use Ps2alerts\Api\Loader\AbstractLoader;
6
use Ps2alerts\Api\QueryObjects\QueryObject;
7
8
abstract class AbstractStatisticsLoader extends AbstractLoader
9
{
10
    /**
11
     * Flags set for workarounds
12
     *
13
     * @var string
14
     */
15
    protected $flags;
16
17
    /**
18
     * Allows setting of workaround flags
19
     *
20
     * @param string $flag
21
     */
22
    public function setFlags($flag)
23
    {
24
        $this->flags = $flag;
25
    }
26
27
    /**
28
     * Retrieves workaround flags
29
     *
30
     * @return string
31
     */
32
    public function getFlags()
33
    {
34
        return $this->flags;
35
    }
36
37
    /**
38
     * @var string
39
     */
40
    protected $type;
41
42
    /**
43
     * Returns the top X of a particular statistic
44
     *
45
     * @param array $post POST variables from the request
46
     *
47
     * @return array
48
     */
49
    public function readStatistics($post)
50
    {
51
        $redisKey = "{$this->getCacheNamespace()}:{$this->getType()}";
52
        $redisKey = $this->appendRedisKey($post, $redisKey);
53
        $post = $this->processPostVars($post);
54
55
        if ($this->checkRedis($redisKey)) {
56
            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...sLoader::readStatistics 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...
57
        }
58
59
        $queryObject = new QueryObject;
60
        $queryObject = $this->setupQueryObject($queryObject, $post);
61
62
        return $this->cacheAndReturn(
63
            $this->repository->read($queryObject),
0 ignored issues
show
Bug introduced by
The property repository does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
64
            $redisKey
65
        );
66
    }
67
68
    /**
69
     * Build a redis key based off inputs provided by the POST request
70
     *
71
     * @param  array  $post
72
     * @param  string $redisKey Redis Key to append to
73
     *
74
     * @return string
75
     */
76
    public function appendRedisKey($post, $redisKey)
77
    {
78
        if (! empty($post['selects'])) {
79
            $whereMD5 = md5($post['selects']);
80
            $redisKey .= "/select:{$whereMD5}";
81
        }
82
83
        if (! empty($post['wheres'])) {
84
            $whereMD5 = md5($post['wheres']);
85
            $redisKey .= "/where:{$whereMD5}";
86
        }
87
88
        if (! empty($post['whereIns'])) {
89
            $whereInMD5 = md5($post['whereIns']);
90
            $redisKey .= "/whereIn:{$whereInMD5}";
91
        }
92
93
        if (! empty($post['orderBy'])) {
94
            $orderMD5 = md5($post['orderBy']);
95
            $redisKey .= "/order:{$orderMD5}";
96
        }
97
98 View Code Duplication
        if (! empty($post['limit'])) {
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...
99
            // Enforce a max limit
100
            if ($post['limit'] > 50) {
101
                $post['limit'] = 50;
102
            }
103
        }
104
105 View Code Duplication
        if (empty($post['limit']) || ! isset($post['limit'])) {
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...
106
            $post['limit'] = 50;
107
        }
108
109
        $redisKey .= "/limit:{$post['limit']}";
110
111
        return $redisKey;
112
    }
113
114
    /**
115
     * De-encode the POST vars for use
116
     *
117
     * @param  array $post
118
     *
119
     * @return array
120
     */
121
    public function processPostVars($post)
122
    {
123
        if (! empty($post['wheres'])) {
124
            $return['wheres'] = json_decode($post['wheres'], true);
0 ignored issues
show
Coding Style Comprehensibility introduced by
$return was never initialized. Although not strictly required by PHP, it is generally a good practice to add $return = 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...
125
            $this->getLogDriver()->addDebug(json_encode($return['wheres']));
126
        }
127
128
        if (! empty($post['whereIns'])) {
129
            $return['whereIns'] = json_decode($post['whereIns'], true);
0 ignored issues
show
Bug introduced by
The variable $return 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...
130
        }
131
132
        if (! empty($post['orderBy'])) {
133
            $return['orderBy'] = json_decode($post['orderBy'], true);
134
        }
135
136 View Code Duplication
        if (empty($post['limit']) || ! isset($post['limit'])) {
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...
137
            $post['limit'] = 10;
138
        }
139
140
        if ($post['limit'] > 50) {
141
            $post['limit'] = 50;
142
        }
143
144
        $return['limit'] = $post['limit'];
145
146
        return $return;
147
    }
148
149
    /**
150
     * Takes common requests and appends them to the query object. Any other
151
     * special requirements will be handled after
152
     *
153
     * @param  Ps2alerts\Api\QueryObjects\QueryObject $queryObject
154
     * @param  array                                  $post
155
     *
156
     * @return Ps2alerts\Api\QueryObjects\QueryObject
157
     */
158
    public function setupQueryObject(QueryObject $queryObject, array $post)
159
    {
160
        if (! empty($post['wheres'])) {
161
            foreach ($post['wheres'] as $key => $value) {
162
                if ($key !== 'lessthan' && $key !== 'morethan') {
163
                    $queryObject->addWhere([
164
                        'col'   => $key,
165
                        'value' => $value
166
                    ]);
167
                }
168
            }
169
170 View Code Duplication
            if (! empty($post['wheres']['lessthan'])) {
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...
171
                foreach ($post['wheres']['lessthan'] as $key => $value) {
172
                    $queryObject->addWhere([
173
                        'col'   => $key,
174
                        'op'    => '<',
175
                        'value' => $value
176
                    ]);
177
                }
178
            }
179
180 View Code Duplication
            if (! empty($post['wheres']['morethan'])) {
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...
181
                foreach ($post['wheres']['morethan'] as $key => $value) {
182
                    $queryObject->addWhere([
183
                        'col'   => $key,
184
                        'op'    => '>',
185
                        'value' => $value
186
                    ]);
187
                }
188
            }
189
        }
190
191
        if (! empty($post['whereIns'])) {
192
            foreach ($post['whereIns'] as $key => $value) {
193
                // Escape strings manually, incase of player IDs etc
194
                foreach ($value as $i => $val) {
195
                    if (is_string($val)) {
196
                        $value[$i] = "'{$val}'";
197
                    }
198
                }
199
200
                $queryObject->addWhereIn([
201
                    'col'   => $key,
202
                    'value' => implode(',', $value) // use implode for WHERE IN (x,x)
203
                ]);
204
            }
205
        }
206
207
        if (! empty($post['orderBy'])) {
208
            $queryObject->setOrderBy(array_keys($post['orderBy'])[0]);
209
            $queryObject->setOrderByDirection(array_values($post['orderBy'])[0]);
210
        }
211
212
        if (! empty($post['limit'])) {
213
            $queryObject->setLimit($post['limit']);
214
        }
215
216
        if (! empty($this->getFlags())) {
217
            // If there are some funky things we have to do, set them.
218
            $queryObject->setFlags($this->getFlags());
219
        }
220
221
        // This should always be set
222
        $queryObject->addWhere([
223
            'col'   => 'Valid',
224
            'value' => '1'
225
        ]);
226
227
        return $queryObject;
228
    }
229
}
230