Completed
Push — master ( 00fae0...ee941a )
by Dan
23:33 queued 15:03
created

Cache::getMultiple()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 7
cts 7
cp 1
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 7
nc 3
nop 2
crap 3
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 \iterable;
14
use Psr\SimpleCache\CacheInterface as SimpleCache;
15
use Psr\SimpleCache\DateInterval;
16
17
/**
18
 * PSR 16 Simple Cache Component
19
 *
20
 * @package Ds\Cache
21
 */
22
class Cache extends AbstractCache implements SimpleCache
23
{
24
    /**
25
     * Persists data in the cache, uniquely referenced by a key with an optional expiration TTL time.
26
     *
27
     * @param string                $key   The key of the item to store.
28
     * @param mixed                 $value The value of the item to store, must be serializable.
29
     * @param null|int|\DateInterval $ttl   Optional. The TTL value of this item. If no value is sent and
30
     *                                     the driver supports TTL then the library may set a default value
31
     *                                     for it or let the driver take care of that.
32
     *
33
     * @return bool True on success and false on failure.
34
     *
35
     * @throws \Psr\SimpleCache\InvalidArgumentException
36
     *   MUST be thrown if the $key string is not a legal value.
37
     */
38 3
    public function set($key, $value, $ttl = null)
39
    {
40
        //convert to timestamp from now.
41 3
        if ($ttl instanceof \DateInterval){
42 1
            $dateTime = new \DateTime();
43 1
            $dateTime->add( $ttl );
44 1
            $ttl = $dateTime->getTimestamp() - time();
45
        }
46
47 3
        if (!is_int($ttl) ||  $ttl === null){
48 1
            throw new InvalidArgumentException('$ttl can only be an instance of \DateInterval, int or null');
49
        }
50
51 2
        return $this->cache->set($key, $value, $ttl);
52
    }
53
54
    /**
55
     * Determines whether an item is present in the cache.
56
     *
57
     * NOTE: It is recommended that has() is only to be used for cache warming type purposes
58
     * and not to be used within your live applications operations for get/set, as this method
59
     * is subject to a race condition where your has() will return true and immediately after,
60
     * another script can remove it making the state of your app out of date.
61
     *
62
     * @param string $key The cache item key.
63
     *
64
     * @return bool
65
     *
66
     * @throws \Psr\SimpleCache\InvalidArgumentException
67
     *   MUST be thrown if the $key string is not a legal value.
68
     */
69 3
    public function has($key)
70
    {
71 3
        $this->_isValidKey($key);
72 2
        return $this->cache->has($key);
73
    }
74
75
    /**
76
     * Fetches a value from the cache.
77
     *
78
     * @param string $key     The unique key of this item in the cache.
79
     * @param mixed  $default Default value to return if the key does not exist.
80
     *
81
     * @return mixed The value of the item from the cache, or $default in case of cache miss.
82
     *
83
     * @throws \Psr\SimpleCache\InvalidArgumentException
84
     *   MUST be thrown if the $key string is not a legal value.
85
     */
86 3
    public function get($key, $default = null)
87
    {
88 3
        $this->_isValidKey($key);
89
90 2
        if ($this->cache->has($key)){
91 1
            return $this->cache->get($key);
92
        }
93
94 1
        return $default;
95
    }
96
97
    /**
98
     * Delete an item from the cache by its unique key.
99
     *
100
     * @param string $key The unique cache key of the item to delete.
101
     *
102
     * @return bool True if the item was successfully removed. False if there was an error.
103
     *
104
     * @throws \Psr\SimpleCache\InvalidArgumentException
105
     *   MUST be thrown if the $key string is not a legal value.
106
     */
107 1
    public function delete($key)
108
    {
109 1
        $this->_isValidKey($key);
110 1
        return $this->cache->delete($key);
111
    }
112
113
114
    /**
115
     * Obtains multiple cache items by their unique keys.
116
     *
117
     * @param iterable $keys    A list of keys that can obtained in a single operation.
118
     * @param mixed    $default Default value to return for keys that do not exist.
119
     *
120
     * @return iterable A list of key => value pairs. Cache keys that do not exist or are stale will have $default as value.
121
     *
122
     * @throws \Psr\SimpleCache\InvalidArgumentException
123
     *   MUST be thrown if $keys is neither an array nor a Traversable,
124
     *   or if any of the $keys are not a legal value.
125
     */
126 1
    public function getMultiple($keys, $default = null)
127
    {
128 1
        $this->_checkTraversable($keys);
129 1
        $result = [];
130
131 1
        foreach ((array)$keys as $key){
132 1
            $cachedItem = $this->cache->get($key);
133 1
            $result[$key] = (null !== $cachedItem) ? $cachedItem : $default;
134
        }
135
136 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...
137
    }
138
139
    /**
140
     * Persists a set of key => value pairs in the cache, with an optional TTL.
141
     *
142
     * @param iterable              $values A list of key => value pairs for a multiple-set operation.
143
     * @param null|int|DateInterval $ttl    Optional. The TTL value of this item. If no value is sent and
144
     *                                      the driver supports TTL then the library may set a default value
145
     *                                      for it or let the driver take care of that.
146
     *
147
     * @return bool True on success and false on failure.
148
     *
149
     * @throws \Psr\SimpleCache\InvalidArgumentException
150
     *   MUST be thrown if $values is neither an array nor a Traversable,
151
     *   or if any of the $values are not a legal value.
152
     */
153 1
    public function setMultiple($values, $ttl = null)
154
    {
155 1
        $this->_checkTraversable($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->_checkTraversable($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
    private function isAssoc(array $arr)
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
219
    {
220
        if (array() === $arr){
221
            return false;
222
        }
223
        return array_keys($arr) !== range(0, count($arr) - 1);
224
    }
225
226
    /**
227
     * Check that $keys are traversable
228
     *
229
     * @param $data
230
     * @throws InvalidArgumentException
231
     * @internal
232
     */
233 4
    private function _checkTraversable($data){
234
235 4
        if (is_array($data)){
236 4
            return;
237
        }
238
239
        if ($data instanceof \Traversable ){
240
            return;
241
        }
242
243
        throw new InvalidArgumentException('Keys must be traversable, in key=>value format');
244
    }
245
246
    /**
247
     * Check for failures when adding multiple entries.
248
     *
249
     * @param array $results
250
     * @return bool
251
     * @internal
252
     */
253 3
    private function _hasFailure(array $results){
254 3
        if (in_array(false, $results)){
255 1
            return true;
256
        }
257 2
        return false;
258
    }
259
}
260