Completed
Push — master ( 7f4329...fe3648 )
by Mehmet
02:49
created

RedisCache::__construct()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

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