Passed
Push — master ( 756562...2dbe85 )
by Dan
14:45 queued 03:38
created

Cache::set()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 15
ccs 8
cts 8
cp 1
rs 9.2
c 1
b 0
f 0
cc 4
eloc 8
nc 4
nop 3
crap 4
1
<?php
2
/**
3
 * Src/Cache/Cache.php
4
 *
5
 * @package     Ds\Cache
6
 * @subpackage  Cache
7
 * @author      Dan Smith <[email protected]>
8
 * @version     v.1 (20/03/2017)
9
 * @copyright   Copyright (c) 2017, Dan Smith
10
 */
11
namespace Ds\Cache;
12
13
use Psr\SimpleCache\CacheInterface as SimpleCache;
14
use Psr\SimpleCache\DateInterval;
15
16
/**
17
 * PSR 16 Simple Cache Component
18
 *
19
 * @package Ds\Cache
20
 */
21
class Cache extends AbstractCache implements SimpleCache
22
{
23
    /**
24
     * Persists data in the cache, uniquely referenced by a key with an optional expiration TTL time.
25
     *
26
     * @param string                $key   The key of the item to store.
27
     * @param mixed                 $value The value of the item to store, must be serializable.
28
     * @param null|int|\DateInterval $ttl   Optional. The TTL value of this item. If no value is sent and
29
     *                                     the driver supports TTL then the library may set a default value
30
     *                                     for it or let the driver take care of that.
31
     *
32
     * @return bool True on success and false on failure.
33
     *
34
     * @throws \Psr\SimpleCache\InvalidArgumentException
35
     *   MUST be thrown if the $key string is not a legal value.
36
     */
37 3
    public function set($key, $value, $ttl = null)
38
    {
39
        //convert to timestamp from now.
40 3
        if ($ttl instanceof \DateInterval){
41 1
            $dateTime = new \DateTime();
42 1
            $dateTime->add( $ttl );
43 1
            $ttl = $dateTime->getTimestamp() - time();
44
        }
45
46 3
        if (!is_int($ttl) ||  $ttl === null){
47 1
            throw new InvalidArgumentException('$ttl can only be an instance of \DateInterval, int or null');
48
        }
49
50 2
        return $this->cache->set($key, $value, $ttl);
51
    }
52
53
    /**
54
     * Determines whether an item is present in the cache.
55
     *
56
     * NOTE: It is recommended that has() is only to be used for cache warming type purposes
57
     * and not to be used within your live applications operations for get/set, as this method
58
     * is subject to a race condition where your has() will return true and immediately after,
59
     * another script can remove it making the state of your app out of date.
60
     *
61
     * @param string $key The cache item key.
62
     *
63
     * @return bool
64
     *
65
     * @throws \Psr\SimpleCache\InvalidArgumentException
66
     *   MUST be thrown if the $key string is not a legal value.
67
     */
68 3
    public function has($key)
69
    {
70 3
        $this->_isValidKey($key);
71 2
        return $this->cache->has($key);
72
    }
73
74
    /**
75
     * Fetches a value from the cache.
76
     *
77
     * @param string $key     The unique key of this item in the cache.
78
     * @param mixed  $default Default value to return if the key does not exist.
79
     *
80
     * @return mixed The value of the item from the cache, or $default in case of cache miss.
81
     *
82
     * @throws \Psr\SimpleCache\InvalidArgumentException
83
     *   MUST be thrown if the $key string is not a legal value.
84
     */
85 3
    public function get($key, $default = null)
86
    {
87 3
        $this->_isValidKey($key);
88
89 2
        if ($this->cache->has($key)){
90 1
            return $this->cache->get($key);
91
        }
92
93 1
        return $default;
94
    }
95
96
    /**
97
     * Delete an item from the cache by its unique key.
98
     *
99
     * @param string $key The unique cache key of the item to delete.
100
     *
101
     * @return bool True if the item was successfully removed. False if there was an error.
102
     *
103
     * @throws \Psr\SimpleCache\InvalidArgumentException
104
     *   MUST be thrown if the $key string is not a legal value.
105
     */
106 1
    public function delete($key)
107
    {
108 1
        $this->_isValidKey($key);
109 1
        return $this->cache->delete($key);
110
    }
111
112
113
    /**
114
     * Obtains multiple cache items by their unique keys.
115
     *
116
     * @param \iterable $keys    A list of keys that can obtained in a single operation.
117
     * @param mixed    $default Default value to return for keys that do not exist.
118
     *
119
     * @return \iterable A list of key => value pairs. Cache keys that do not exist or are stale will have $default as value.
120
     *
121
     * @throws \Psr\SimpleCache\InvalidArgumentException
122
     *   MUST be thrown if $keys is neither an array nor a Traversable,
123
     *   or if any of the $keys are not a legal value.
124
     */
125 1
    public function getMultiple($keys, $default = null)
126
    {
127 1
        $this->_isTraversable($keys);
128 1
        $result = [];
129
130 1
        foreach ((array)$keys as $key){
131 1
            $cachedItem = $this->cache->get($key);
132 1
            $result[$key] = (null !== $cachedItem) ? $cachedItem : $default;
133
        }
134
135 1
        return (array)$result;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return (array) $result; (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...
136
    }
137
138
    /**
139
     * Persists a set of key => value pairs in the cache, with an optional TTL.
140
     *
141
     * @param \iterable              $values A list of key => value pairs for a multiple-set operation.
142
     * @param null|int|DateInterval $ttl    Optional. The TTL value of this item. If no value is sent and
143
     *                                      the driver supports TTL then the library may set a default value
144
     *                                      for it or let the driver take care of that.
145
     *
146
     * @return bool True on success and false on failure.
147
     *
148
     * @throws \Psr\SimpleCache\InvalidArgumentException
149
     *   MUST be thrown if $values is neither an array nor a Traversable,
150
     *   or if any of the $values are not a legal value.
151
     */
152 1
    public function setMultiple($values, $ttl = null)
153
    {
154 1
        $this->_hasKeys($values);
155 1
        $this->_isTraversable($values);
156 1
        $results = [];
157
158 1
        foreach ((array)$values as $key => $value){
159 1
            $results[] = $this->cache->set($key, $value, $ttl);
160
        }
161
162 1
        if ($this->_hasFailure($results)){
163
            return false;
164
        }
165
166 1
        return true;
167
    }
168
169
    /**
170
     * Deletes multiple cache items in a single operation.
171
     *
172
     * @param \iterable $keys A list of string-based keys to be deleted.
173
     *
174
     * @return bool True if the items were successfully removed. False if there was an error.
175
     *
176
     * @throws \Psr\SimpleCache\InvalidArgumentException
177
     *   MUST be thrown if $keys is neither an array nor a Traversable,
178
     *   or if any of the $keys are not a legal value.
179
     */
180 2
    public function deleteMultiple($keys)
181
    {
182 2
        $this->_isTraversable($keys);
183 2
        $results = [];
184
185 2
        foreach ((array)$keys as $key){
186 2
            $results[] = $this->cache->delete($key);
187
        }
188
189 2
        if ($this->_hasFailure($results)){
190 1
            return false;
191
        }
192
193 1
        return true;
194
    }
195
196
    /**
197
     * Wipes clean the entire cache's keys.
198
     *
199
     * @return bool True on success and false on failure.
200
     */
201 1
    public function clear()
202
    {
203 1
        return $this->cache->clear();
204
    }
205
206
    /**
207
     * Check that provided key is valid.
208
     *
209
     * @param $key
210
     * @throws InvalidArgumentException
211
     */
212 7
    private function _isValidKey($key){
213 7
        if (!is_string($key)){
214 2
            throw new InvalidArgumentException('provided key must be a valid string');
215
        }
216 5
    }
217
218
    /**
219
     * Check that $keys are traversable
220
     *
221
     * @param $data
222
     * @throws InvalidArgumentException
223
     * @return bool
224
     * @internal
225
     */
226 7
    private function _isTraversable($data){
227
228 7
        if (is_array($data) || $data instanceof \Traversable){
229 6
            return true;
230
        }
231
232 1
        throw new InvalidArgumentException('Keys must be traversable');
233
    }
234
235
    /**
236
     * @param array $arr
237
     * @return bool
238
     * @throws InvalidArgumentException
239
     */
240 3
    private function _hasKeys(array $arr)
241
    {
242 3
        if (array() === $arr || array_keys($arr) === range(0, count($arr) - 1)){
243 1
            throw new InvalidArgumentException('Keys missing');
244
        }
245
246 2
        return true;
247
    }
248
249
    /**
250
     * Check for failures when adding multiple entries.
251
     *
252
     * @param array $results
253
     * @return bool
254
     * @internal
255
     */
256 5
    private function _hasFailure(array $results){
257 5
        if (in_array(false, $results)){
258 2
            return true;
259
        }
260 3
        return false;
261
    }
262
}
263