Completed
Push — master ( 45aada...26ef87 )
by Matthew
02:32
created

AbstractStatisticsLoader   A

Complexity

Total Complexity 20

Size/Duplication

Total Lines 110
Duplicated Lines 16.36 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 4
Bugs 0 Features 1
Metric Value
wmc 20
c 4
b 0
f 1
lcom 1
cbo 2
dl 18
loc 110
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A setFlags() 0 4 1
A getFlags() 0 4 1
C appendRedisKey() 9 25 7
B processPostVars() 9 22 6
B readStatistics() 0 36 5

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
    protected $flags;
11
12
    public function setFlags($flag)
13
    {
14
        $this->flags = $flag;
15
    }
16
17
    public function getFlags()
18
    {
19
        return $this->flags;
20
    }
21
22
    /**
23
     * @var string
24
     */
25
    protected $type;
26
27
    public function appendRedisKey($post, $redisKey)
28
    {
29
        if (! empty($post['wheres'])) {
30
            $whereMD5 = md5($post['wheres']);
31
            $redisKey .= "/{$whereMD5}";
32
        }
33
        if (! empty($post['orderBy'])) {
34
            $orderMD5 = md5($post['orderBy']);
35
            $redisKey .= "/{$orderMD5}";
36
        }
37 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...
38
            // Enforce a max limit
39
            if ($post['limit'] > 50) {
40
                $post['limit'] = 50;
41
            }
42
        }
43
44 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...
45
            $post['limit'] = 10;
46
        }
47
48
        $redisKey .= "/{$post['limit']}";
49
50
        return $redisKey;
51
    }
52
53
    public function processPostVars($post)
54
    {
55 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...
56
            $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...
57
        }
58
59 View Code Duplication
        if (! empty($post['orderBy'])) {
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...
60
            $return['orderBy'] = json_decode($post['orderBy'], 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...
61
        }
62
63 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...
64
            $post['limit'] = 10;
65
        }
66
67
        if ($post['limit'] > 50) {
68
            $post['limit'] = 50;
69
        }
70
71
        $return['limit'] = $post['limit'];
72
73
        return $return;
74
    }
75
76
    /**
77
     * Returns the top X of a particular statistic
78
     *
79
     * @return array
80
     */
81
    public function readStatistics($post)
82
    {
83
        $redisKey = "{$this->getCacheNamespace()}:{$this->getType()}";
84
        $redisKey = $this->appendRedisKey($post, $redisKey);
85
        $post = $this->processPostVars($post);
86
87
        if ($this->checkRedis($redisKey)) {
88
            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...
89
        }
90
91
        $queryObject = new QueryObject;
92
93
        foreach ($post['wheres'] as $key => $value) {
94
            $queryObject->addWhere([
95
                'col' => array_keys($value)[0],
96
                'value' => array_values($value)[0]
97
            ]);
98
        }
99
100
        if (! empty($post['orderBy'])) {
101
            $queryObject->setOrderBy(array_keys($post['orderBy'])[0]);
102
            $queryObject->setOrderByDirection(array_values($post['orderBy'])[0]);
103
        }
104
105
        $queryObject->setLimit($post['limit']);
106
107
        if (! empty($this->getFlags())) {
108
            // If there are some funky things we have to do, set them.
109
            $queryObject->setFlags($this->getFlags());
110
        }
111
112
        return $this->cacheAndReturn(
113
            $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...
114
            $redisKey
115
        );
116
    }
117
}
118