Completed
Pull Request — master (#113)
by Joshua
52:02 queued 43:08
created

PhpRedis::sanitizeRedisKey()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3

Duplication

Lines 3
Ratio 100 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 3
loc 3
ccs 0
cts 0
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 2
1
<?php
2
3
4
namespace Noxlogic\RateLimitBundle\Service\Storage;
5
6
7
use Noxlogic\RateLimitBundle\Service\RateLimitInfo;
8
9 View Code Duplication
class PhpRedis implements StorageInterface
0 ignored issues
show
Duplication introduced by
This class 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...
10
{
11
    /**
12
    * @var \Redis
13
    */
14
    protected $client;
15
16 5
    public function __construct(\Redis $client)
17
    {
18 5
        $this->client = $client;
19 5
    }
20
21 6
    public function getRateInfo($key)
22
    {
23 6
        $key = $this->sanitizeRedisKey($key);
24 6
25 2
        $info = $this->client->hgetall($key);
26
        if (!isset($info['limit']) || !isset($info['calls']) || !isset($info['reset'])) {
27
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type declared by the interface Noxlogic\RateLimitBundle...eInterface::getRateInfo of type Noxlogic\RateLimitBundle\Service\RateLimitInfo.

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...
28 4
        }
29 4
30 4
        $rateLimitInfo = new RateLimitInfo();
31 4
        $rateLimitInfo->setLimit($info['limit']);
32
        $rateLimitInfo->setCalls($info['calls']);
33 4
        $rateLimitInfo->setResetTimestamp($info['reset']);
34
35
        return $rateLimitInfo;
36 4
    }
37
38 4
    public function limitRate($key)
39 4
    {
40 2
        $key = $this->sanitizeRedisKey($key);
41
42
        $info = $this->getRateInfo($key);
0 ignored issues
show
Bug introduced by
It seems like $key defined by $this->sanitizeRedisKey($key) on line 40 can also be of type array<integer,string>; however, Noxlogic\RateLimitBundle...PhpRedis::getRateInfo() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
43 2
        if (!$info) {
44 2
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type declared by the interface Noxlogic\RateLimitBundle...ageInterface::limitRate of type Noxlogic\RateLimitBundle\Service\RateLimitInfo.

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...
45
        }
46 2
47
        $calls = $this->client->hincrby($key, 'calls', 1);
48
        $info->setCalls($calls);
49 2
50
        return $info;
51 2
    }
52
53 2
    public function createRate($key, $limit, $period)
54 2
    {
55 2
        $key = $this->sanitizeRedisKey($key);
56 2
57
        $reset = time() + $period;
58 2
59 2
        $this->client->hset($key, 'limit', $limit);
60 2
        $this->client->hset($key, 'calls', 1);
61 2
        $this->client->hset($key, 'reset', $reset);
62
        $this->client->expire($key, $period);
63 2
64
        $rateLimitInfo = new RateLimitInfo();
65
        $rateLimitInfo->setLimit($limit);
66 2
        $rateLimitInfo->setCalls(1);
67
        $rateLimitInfo->setResetTimestamp($reset);
68 2
69
        return $rateLimitInfo;
70 2
    }
71
72
    public function resetRate($key)
73
    {
74
        $key = $this->sanitizeRedisKey($key);
75
76
        $this->client->del($key);
77
78
        return true;
79
    }
80
81
    /**
82
     * Sanitizies key so it can be used safely in REDIS
83
     *
84
     * @param $key
85
     * @return string|string[]
86
     */
87
    protected function sanitizeRedisKey($key) {
88
        return str_replace(str_split('@{}()/\:'), '_', $key);
89
    }
90
91
}
92