Completed
Push — master ( 1b587d...1ebcfd )
by Mehmet
02:56
created

RedisCache::connect()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 8

Duplication

Lines 10
Ratio 100 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 10
loc 10
rs 9.4285
cc 1
eloc 8
nc 1
nop 1
1
<?php
2
3
namespace Soupmix\Cache;
4
5
use Redis;
6
7
class RedisCache implements CacheInterface
8
{
9
10
    private static $defaults = [
11
        'persistent' => null,
12
        'bucket' => 'default',
13
        'dbIndex' => 0,
14
        'port' => 6379,
15
        'timeout' => 2.5,
16
        'persistentId' => null,
17
        'reconnectAttempt' => 100
18
    ];
19
20
    private $serializer = Redis::SERIALIZER_PHP;
21
22
    public $handler = null;
23
    /**
24
     * Connect to Redis service
25
     *
26
     * @param array $config Configuration values that has dbIndex name and host's IP address
27
     *
28
     */
29
    public function __construct(array $config)
30
    {
31
        $this->handler = new Redis();
32
        $redisConfig= $this::$defaults;
33
        foreach ($config as $key=>$value) {
34
            $redisConfig[$key] = $value;
35
        }
36
        if (file_exists('igbinary_serialize')) {
37
            $this->serializer = Redis::SERIALIZER_IGBINARY;
38
        }
39
        if ( isset($redisConfig['persistent']) && ($redisConfig['persistent'] === true)) {
40
            return $this->connect($redisConfig);
0 ignored issues
show
Bug introduced by
Constructors do not have meaningful return values, anything that is returned from here is discarded. Are you sure this is correct?
Loading history...
41
        }
42
        $this->persistentConnect($redisConfig);
43
    }
44
45 View Code Duplication
    private function connect( array $redisConfig){
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...
46
        $this->handler->connect(
47
            $redisConfig['host'],
48
            $redisConfig['port'],
49
            $redisConfig['timeout'],
50
            null,
51
            $redisConfig['reconnectAttempt']
52
        );
53
        return $this->handler->select($redisConfig['dbIndex']);
54
    }
55
56 View Code Duplication
    private function persistentConnect( array $redisConfig){
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...
57
        $this->handler->pconnect(
58
            $redisConfig['host'],
59
            $redisConfig['port'],
60
            $redisConfig['timeout'],
61
            $redisConfig['persistentId']
62
        );
63
        return $this->handler->select($redisConfig['dbIndex']);
64
65
    }
66
67
    /**
68
     * Fetch a value from the cache.
69
     *
70
     * @param string $key The unique key of this item in the cache
71
     *
72
     * @return mixed The value of the item from the cache, or null in case of cache miss
73
     */
74
    public function get($key)
75
    {
76
        $value = $this->handler->get($key);
77
        return ($value) ? $this->unserialize($value) : null;
78
    }
79
    /**
80
     * Persist data in the cache, uniquely referenced by a key with an optional expiration TTL time.
81
     *
82
     * @param string $key The key of the item to store
83
     * @param mixed $value The value of the item to store
84
     * @param null|integer|DateInterval $ttl Optional. The TTL value of this item. If no value is sent and the driver supports TTL
85
     *                                       then the library may set a default value for it or let the driver take care of that.
86
     *
87
     * @return bool True on success and false on failure
88
     */
89
    public function set($key, $value, $ttl = null){
90
        $ttl = intval($ttl);
91
        $value = $this->serialize($value);
92
        if($ttl ==0 ){
93
            return $this->handler->set($key, $value);
94
        }
95
        return $this->handler->set($key, $value, $ttl);
96
    }
97
98
    private function serialize($value){
99
        return ($this->serializer === Redis::SERIALIZER_IGBINARY) ? igbinary_serialize($value) : serialize($value);
100
    }
101
102
    private function unserialize($value){
103
        return ($this->serializer === Redis::SERIALIZER_IGBINARY) ? igbinary_unserialize($value) : unserialize($value);
104
    }
105
    /**
106
     * Delete an item from the cache by its unique key
107
     *
108
     * @param string $key The unique cache key of the item to delete
109
     *
110
     * @return bool True on success and false on failure
111
     */
112
    public function delete($key){
113
        return (bool) $this->handler->delete($key);
114
    }
115
    /**
116
     * Wipe clean the entire cache's keys
117
     *
118
     * @return bool True on success and false on failure
119
     */
120
    public function clear(){
121
        return $this->handler->flushDb();
122
    }
123
    /**
124
     * Obtain multiple cache items by their unique keys
125
     *
126
     * @param array|Traversable $keys A list of keys that can obtained in a single operation.
127
     *
128
     * @return array An array of key => value pairs. Cache keys that do not exist or are stale will have a value of null.
129
     */
130
    public function getMultiple($keys)
131
    {
132
        return array_combine($keys, $this->handler->mGet($keys));
133
    }
134
    /**
135
     * Persisting a set of key => value pairs in the cache, with an optional TTL.
136
     *
137
     * @param array|Traversable         $items An array of key => value pairs for a multiple-set operation.
138
     * @param null|integer|DateInterval $ttl   Optional. The amount of seconds from the current time that the item will exist in the cache for.
139
     *                                         If this is null then the cache backend will fall back to its own default behaviour.
140
     *
141
     * @return bool True on success and false on failure
142
     */
143
    public function setMultiple($items, $ttl = null)
144
    {
145
        if (($ttl === null) || ($ttl === 0)) {
146
            return $this->handler->mSet($items);
147
        }
148
149
        $return =[];
150
        foreach ($items as $key=>$value) {
151
            $return[$key] =  $this->set($key, $value, $ttl);
152
        }
153
        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 Soupmix\Cache\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...
154
    }
155
    /**
156
     * Delete multiple cache items in a single operation
157
     *
158
     * @param array|Traversable $keys The array of string-based keys to be deleted
159
     *
160
     * @return bool True on success and false on failure
161
     */
162
    public function deleteMultiple($keys)
163
    {
164
        $return =[];
165
        foreach ($keys as $key) {
166
            $return[$key] = (bool) $this->delete($key);
167
        }
168
        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 Soupmix\Cache\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...
169
    }
170
    /**
171
     * Increment a value atomically in the cache by its step value, which defaults to 1
172
     *
173
     * @param string  $key  The cache item key
174
     * @param integer $step The value to increment by, defaulting to 1
175
     *
176
     * @return int|bool The new value on success and false on failure
177
     */
178
    public function increment($key, $step = 1)
179
    {
180
        return $this->handler->incr($key, $step);
181
    }
182
    /**
183
     * Decrement a value atomically in the cache by its step value, which defaults to 1
184
     *
185
     * @param string  $key  The cache item key
186
     * @param integer $step The value to decrement by, defaulting to 1
187
     *
188
     * @return int|bool The new value on success and false on failure
189
     */
190
    public function decrement($key, $step = 1)
191
    {
192
        return $this->handler->decr($key, $step);
193
    }
194
}