Completed
Push — master ( 412b6e...c5c325 )
by Mehmet
04:00
created

RedisCache::checkReservedCharacters()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 5.024

Importance

Changes 3
Bugs 0 Features 2
Metric Value
c 3
b 0
f 2
dl 0
loc 14
ccs 6
cts 10
cp 0.6
rs 9.2
cc 4
eloc 8
nc 4
nop 1
crap 5.024
1
<?php
2
3
namespace Soupmix\Cache;
4
5
use Soupmix\Cache\Exceptions\InvalidArgumentException;
6
use Psr\SimpleCache\CacheInterface;
7
use Redis;
8
9
class RedisCache implements CacheInterface
10
{
11
    const PSR16_RESERVED_CHARACTERS = ['{','}','(',')','/','@',':'];
12
13
    private $handler;
14
15
16
    /**
17
     * Connect to Redis service
18
     *
19
     * @param Redis $handler Configuration values that has dbIndex name and host's IP address
20
     *
21
     */
22 8
    public function __construct(Redis $handler)
23
    {
24 8
        if (defined('Redis::SERIALIZER_IGBINARY') && extension_loaded('igbinary')) {
25
            $handler->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_IGBINARY);
26
        }
27 8
        $this->handler = $handler;
28 8
    }
29
30
    public function getConnection()
31
    {
32
        return $this->handler;
33
    }
34
35
    /**
36
     * {@inheritDoc}
37
     */
38 2
    public function get($key, $default = null)
39
    {
40 2
        $value = $this->handler->get($key);
41 2
        return $value ? $value : $default;
42
    }
43
44
    /**
45
     * {@inheritDoc}
46
     */
47 2
    public function set($key, $value, $ttl = null)
48
    {
49 2
        if ($ttl instanceof DateInterval) {
0 ignored issues
show
Bug introduced by
The class Soupmix\Cache\DateInterval does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
50
            $ttl = (new DateTime('now'))->add($ttl)->getTimeStamp() - time();
51
        }
52 2
        $setTtl = (int) $ttl;
53 2
        if ($setTtl === 0) {
54 2
            return $this->handler->set($key, $value);
55
        }
56
        return $this->handler->setex($key, $ttl, $value);
57
    }
58
59
    /**
60
     * {@inheritDoc}
61
     */
62 4
    public function delete($key)
63
    {
64 4
        return (bool) $this->handler->delete($key);
65
    }
66
    /**
67
     * {@inheritDoc}
68
     */
69 8
    public function clear()
70
    {
71 8
        return $this->handler->flushDB();
72
    }
73
    /**
74
     * {@inheritDoc}
75
     */
76 2
    public function getMultiple($keys, $default = null)
77
    {
78 2
        $defaults = array_fill(0, count($keys), $default);
79 2
        foreach ($keys as $key) {
80 2
            $this->checkKeysValidity($key);
81 2
        }
82 2
        return array_merge(array_combine($keys, $this->handler->mget($keys)), $defaults);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return array_merge(array...et($keys)), $defaults); (array) is incompatible with the return type declared by the interface Psr\SimpleCache\CacheInterface::getMultiple of type Psr\SimpleCache\iterable.

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...
83
    }
84
    /**
85
     * {@inheritDoc}
86
     */
87 2
    public function setMultiple($values, $ttl = null)
88
    {
89 2
        foreach ($values as $key => $value) {
90 2
            $this->checkKeysValidity($key);
91 2
        }
92 2
        if ($ttl instanceof DateInterval) {
0 ignored issues
show
Bug introduced by
The class Soupmix\Cache\DateInterval does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
93
            $ttl = (new DateTime('now'))->add($ttl)->getTimeStamp() - time();
94
        }
95 2
        $setTtl = (int) $ttl;
96 2
        if ($setTtl === 0) {
97 2
            return $this->handler->mset($values);
98
        }
99
        $return =[];
100
        foreach ($values as $key => $value) {
101
            $return[$key] =  $this->set($key, $value, $ttl);
0 ignored issues
show
Bug introduced by
It seems like $ttl defined by (new \Soupmix\Cache\Date...getTimeStamp() - time() on line 93 can also be of type double; however, Soupmix\Cache\RedisCache::set() does only seem to accept null|integer|object<Psr\SimpleCache\DateInterval>, 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...
102
        }
103
        return $return;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $return; (array) is incompatible with the return type declared by the interface Psr\SimpleCache\CacheInterface::setMultiple of type boolean.

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...
104
    }
105
    /**
106
     * {@inheritDoc}
107
     */
108 2
    public function deleteMultiple($keys)
109
    {
110 2
        foreach ($keys as $key) {
111 2
            $this->checkKeysValidity($key);
112 2
        }
113 2
        $return =[];
114 2
        foreach ($keys as $key) {
115 2
            $return[$key] = (bool) $this->delete($key);
116 2
        }
117 2
        return $return;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $return; (array) is incompatible with the return type declared by the interface Psr\SimpleCache\CacheInterface::deleteMultiple of type boolean.

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...
118
    }
119
    /**
120
     * Increment a value atomically in the cache by its step value, which defaults to 1
121
     *
122
     * @param string  $key  The cache item key
123
     * @param integer $step The value to increment by, defaulting to 1
124
     *
125
     * @return int|bool The new value on success and false on failure
126
     */
127 2
    public function increment($key, $step = 1)
128
    {
129 2
        return $this->handler->incr($key, $step);
130
    }
131
    /**
132
     * Decrement a value atomically in the cache by its step value, which defaults to 1
133
     *
134
     * @param string  $key  The cache item key
135
     * @param integer $step The value to decrement by, defaulting to 1
136
     *
137
     * @return int|bool The new value on success and false on failure
138
     */
139 2
    public function decrement($key, $step = 1)
140
    {
141 2
        return $this->handler->decr($key, $step);
142
    }
143
144
145
146
147
    /**
148
     * {@inheritDoc}
149
     */
150
    public function has($key)
151
    {
152
        $this->checkKeysValidity($key);
153
        return $this->handler->exists($key);
154
    }
155
156 2
    private function checkKeysValidity($key)
157
    {
158 2
        if (!is_string($key)) {
159
            $message = sprintf('Key %s is not a string.', $key);
160
            throw new InvalidArgumentException($message);
161
        }
162 2
        foreach (self::PSR16_RESERVED_CHARACTERS as $needle) {
163 2
            if (strpos($key, $needle) !== false) {
164
                $message = sprintf('Key %s has not a legal value.', $key);
165
                throw new InvalidArgumentException($message);
166
            }
167 2
        }
168 2
    }
169
}
170