Completed
Push — master ( 1768c8...189bb6 )
by Matthew
03:41
created

AbstractStatisticsLoader::readStatistics()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 18
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 1
Metric Value
c 3
b 0
f 1
dl 0
loc 18
rs 9.4286
cc 2
eloc 11
nc 2
nop 1
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);
0 ignored issues
show
Documentation introduced by
$queryObject is of type object<Ps2alerts\Api\QueryObjects\QueryObject>, but the function expects a object<Ps2alerts\Api\Loa...eryObjects\QueryObject>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
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 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...
98
            // Enforce a max limit
99
            if ($post['limit'] > 50) {
100
                $post['limit'] = 50;
101
            }
102
        }
103
104 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...
105
            $post['limit'] = 10;
106
        }
107
108
        $redisKey .= "/limit{$post['limit']}";
109
110
        return $redisKey;
111
    }
112
113
    /**
114
     * De-encode the POST vars for use
115
     *
116
     * @param  array $post
117
     *
118
     * @return array
119
     */
120
    public function processPostVars($post)
121
    {
122
        if (! empty($post['wheres'])) {
123
            $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...
124
            $this->getLogDriver()->addDebug(json_encode($return['wheres']));
125
        }
126
127
        if (! empty($post['whereIns'])) {
128
            $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...
129
        }
130
131
        if (! empty($post['orderBy'])) {
132
            $return['orderBy'] = json_decode($post['orderBy'], true);
133
        }
134
135 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...
136
            $post['limit'] = 10;
137
        }
138
139
        if ($post['limit'] > 50) {
140
            $post['limit'] = 50;
141
        }
142
143
        $return['limit'] = $post['limit'];
144
145
        return $return;
146
    }
147
148
    /**
149
     * Takes common requests and appends them to the query object. Any other
150
     * special requirements will be handled after
151
     *
152
     * @param  Ps2alerts\Api\QueryObjects\QueryObject $queryObject
153
     * @param  array                                  $post
154
     *
155
     * @return Ps2alerts\Api\QueryObjects\QueryObject
156
     */
157
    public function setupQueryObject($queryObject, $post)
158
    {
159
        if (! empty($post['wheres'])) {
160
            foreach ($post['wheres'] as $key => $value) {
161
                $queryObject->addWhere([
162
                    'col'   => $key,
163
                    'value' => $value
164
                ]);
165
            }
166
        }
167
168
        if (! empty($post['whereIns'])) {
169
            foreach ($post['whereIns'] as $key => $value) {
170
                // Escape strings manually, incase of player IDs etc
171
                foreach ($value as $i => $val) {
172
                    if (is_string($val)) {
173
                        $value[$i] = "'{$val}'";
174
                    }
175
                }
176
177
                $queryObject->addWhereIn([
178
                    'col'   => $key,
179
                    'value' => implode(',', $value) // use implode for WHERE IN (x,x)
180
                ]);
181
            }
182
        }
183
184
        if (! empty($post['orderBy'])) {
185
            $queryObject->setOrderBy(array_keys($post['orderBy'])[0]);
186
            $queryObject->setOrderByDirection(array_values($post['orderBy'])[0]);
187
        }
188
189
        if (! empty($post['limit'])) {
190
            $queryObject->setLimit($post['limit']);
191
        }
192
193
        if (! empty($this->getFlags())) {
194
            // If there are some funky things we have to do, set them.
195
            $queryObject->setFlags($this->getFlags());
196
        }
197
198
        // This should always be set
199
        $queryObject->addWhere([
200
            'col'   => 'Valid',
201
            'value' => '1'
202
        ]);
203
204
        return $queryObject;
205
    }
206
}
207