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

AbstractStatisticsLoader::appendRedisKey()   C

Complexity

Conditions 7
Paths 32

Size

Total Lines 28
Code Lines 16

Duplication

Lines 8
Ratio 28.57 %

Importance

Changes 8
Bugs 2 Features 3
Metric Value
c 8
b 2
f 3
dl 8
loc 28
rs 6.7273
cc 7
eloc 16
nc 32
nop 2
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 View Code Duplication
    public function readStatistics($post)
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...
50
    {
51
        $redisKey = "{$this->getCacheNamespace()}:{$this->getType()}";
52
        $redisKey = $this->appendRedisKey($post, $redisKey);
53
        $post = $this->processPostVars($post);
0 ignored issues
show
Bug introduced by
The method processPostVars() does not exist on Ps2alerts\Api\Loader\Sta...bstractStatisticsLoader. 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...
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 View Code Duplication
        if (! empty($post['selects'])) {
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...
79
            $whereMD5 = md5(json_encode($post['selects']));
80
            $redisKey .= "/select:{$whereMD5}";
81
        }
82
83 View Code Duplication
        if (! empty($post['wheres'])) {
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...
84
            $whereMD5 = md5(json_encode($post['wheres']));
85
            $redisKey .= "/where:{$whereMD5}";
86
        }
87
88
        if (! empty($post['whereIns'])) {
89
            $whereInMD5 = md5(json_encode($post['whereIns']));
90
            $redisKey .= "/whereIn:{$whereInMD5}";
91
        }
92
93
        if (! empty($post['orderBy'])) {
94
            $orderMD5 = md5(json_encode($post['orderBy']));
95
            $redisKey .= "/order:{$orderMD5}";
96
        }
97
98
        if (empty($post['limit']) || ! isset($post['limit'])) {
99
            $redisKey .= "/limit:{$post['limit']}";
100
        }
101
102
        return $redisKey;
103
    }
104
105
    /**
106
     * De-encode the POST from application/json vars for use
107
     *
108
     * @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...
109
     *
110
     * @return array
111
     */
112
    public function processPost()
113
    {
114
        $json = file_get_contents('php://input');
115
        $post = json_decode($json);
116
117
        // Cheat, dirty hack to get everything out as an array
118
        $post = json_decode(json_encode($post), true);
119
120
        if (empty($post['limit']) || ! isset($post['limit'])) {
121
            $post['limit'] = 10;
122
        }
123
124
        if ($post['limit'] > 50) {
125
            $post['limit'] = 50;
126
        }
127
128
        return $post;
129
    }
130
131
    /**
132
     * Takes common requests and appends them to the query object. Any other
133
     * special requirements will be handled after
134
     *
135
     * @param  Ps2alerts\Api\QueryObjects\QueryObject $queryObject
136
     * @param  array                                  $post
137
     *
138
     * @return Ps2alerts\Api\QueryObjects\QueryObject
139
     */
140
    public function setupQueryObject(QueryObject $queryObject, array $post)
141
    {
142
        if (! empty($post['wheres'])) {
143
            foreach ($post['wheres'] as $key => $value) {
144
                if ($key !== 'lessthan' && $key !== 'morethan') {
145
                    $queryObject->addWhere([
146
                        'col'   => $key,
147
                        'value' => $value
148
                    ]);
149
                }
150
            }
151
152 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...
153
                foreach ($post['wheres']['lessthan'] as $key => $value) {
154
                    $queryObject->addWhere([
155
                        'col'   => $key,
156
                        'op'    => '<',
157
                        'value' => $value
158
                    ]);
159
                }
160
            }
161
162 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...
163
                foreach ($post['wheres']['morethan'] as $key => $value) {
164
                    $queryObject->addWhere([
165
                        'col'   => $key,
166
                        'op'    => '>',
167
                        'value' => $value
168
                    ]);
169
                }
170
            }
171
        }
172
173
        if (! empty($post['whereIns'])) {
174
            foreach ($post['whereIns'] as $key => $value) {
175
                // Escape strings manually, incase of player IDs etc
176
                foreach ($value as $i => $val) {
177
                    if (is_string($val)) {
178
                        $value[$i] = "'{$val}'";
179
                    }
180
                }
181
182
                $queryObject->addWhereIn([
183
                    'col'   => $key,
184
                    'value' => implode(',', $value) // use implode for WHERE IN (x,x)
185
                ]);
186
            }
187
        }
188
189
        if (! empty($post['orderBy'])) {
190
            $queryObject->setOrderBy(array_keys($post['orderBy'])[0]);
191
            $queryObject->setOrderByDirection(array_values($post['orderBy'])[0]);
192
        }
193
194
        if (! empty($post['limit'])) {
195
            $queryObject->setLimit($post['limit']);
196
        }
197
198
        if (! empty($this->getFlags())) {
199
            // If there are some funky things we have to do, set them.
200
            $queryObject->setFlags($this->getFlags());
201
        }
202
203
        // This should always be set
204
        $queryObject->addWhere([
205
            'col'   => 'Valid',
206
            'value' => '1'
207
        ]);
208
209
        return $queryObject;
210
    }
211
}
212