Failed Conditions
Push — v3.x ( 1f61fa...b0fa1f )
by Chad
02:14
created

InMemoryCache::deleteMultiple()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 1
1
<?php
2
3
namespace Chadicus\Marvel\Api\Cache;
4
5
use DominionEnterprises\Util\Arrays;
6
use Psr\SimpleCache\CacheInterface;
7
8
/**
9
 * A PSR-16 implementation which stores data in an array.
10
 */
11
final class InMemoryCache extends AbstractCache implements CacheInterface
12
{
13
    /**
14
     * Array containing the cached data.
15
     *
16
     * @var array
17
     */
18
    private $cache = [];
19
20
    /**
21
     * Fetches a value from the cache.
22
     *
23
     * @param string $key     The unique key of this item in the cache.
24
     * @param mixed  $default Default value to return if the key does not exist.
25
     *
26
     * @return mixed The value of the item from the cache, or $default in case of cache miss.
27
     *
28
     * @throws InvalidArgumentException Thrown if the $key string is not a legal value.
29
     */
30
    public function get($key, $default = null)
31
    {
32
        $this->verifyKey($key);
33
        $cache = Arrays::get($this->cache, $key);
34
        if ($cache === null) {
35
            return $default;
36
        }
37
38
        if ($cache['expires'] < time()) {
39
            unset($this->cache[$key]);
40
            return $default;
41
        }
42
43
        return $cache['response'];
44
    }
45
46
    /**
47
     * Persists data in the cache, uniquely referenced by a key with an optional expiration TTL time.
48
     *
49
     * @param string                $key   The key of the item to store.
50
     * @param mixed                 $value The value of the item to store, must be serializable.
51
     * @param null|int|DateInterval $ttl   Optional. The TTL value of this item. If no value is sent and
52
     *                                     the driver supports TTL then the library may set a default value
53
     *                                     for it or let the driver take care of that.
54
     *
55
     * @return bool True on success and false on failure.
56
     *
57
     * @throws InvalidArgumentException Thrown if the $key string is not a legal value.
58
     */
59
    public function set($key, $value, $ttl = null)
60
    {
61
        $this->verifyKey($key);
62
63
        $this->cache[$key] = [
64
            'response' => $value,
65
            'expires' => $this->getExpires($ttl),
66
        ];
67
68
        return true;
69
    }
70
71
    /**
72
     * Delete an item from the cache by its unique key.
73
     *
74
     * @param string $key The unique cache key of the item to delete.
75
     *
76
     * @return bool True if the item was successfully removed. False if there was an error.
77
     *
78
     * @throws InvalidArgumentException Thrown if the $key string is not a legal value.
79
     */
80
    public function delete($key)
81
    {
82
        $this->verifyKey($key);
83
        unset($this->cache[$key]);
84
        return true;
85
    }
86
87
    /**
88
     * Wipes clean the entire cache's keys.
89
     *
90
     * @return bool True on success and false on failure.
91
     */
92
    public function clear()
93
    {
94
        $this->cache = [];
95
        return true;
96
    }
97
98
    /**
99
     * Obtains multiple cache items by their unique keys.
100
     *
101
     * @param iterable $keys    A list of keys that can obtained in a single operation.
102
     * @param mixed    $default Default value to return for keys that do not exist.
103
     *
104
     * @return iterable A list of key => value pairs. Cache keys that do not exist or are stale will have $default as value.
105
     *
106
     * @throws InvalidArgumentException Thrown if the $key string is not a legal value.
107
     */
108
    public function getMultiple($keys, $default = null)
109
    {
110
        $items = [];
111
        foreach ($keys as $key) {
112
            $items[$key] = $this->get($key, $default);
113
        }
114
115
        return $items;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $items; (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...
116
    }
117
118
    /**
119
     * Persists a set of key => value pairs in the cache, with an optional TTL.
120
     *
121
     * @param iterable              $values A list of key => value pairs for a multiple-set operation.
122
     * @param null|int|DateInterval $ttl    Optional. The TTL value of this item. If no value is sent and
123
     *                                      the driver supports TTL then the library may set a default value
124
     *                                      for it or let the driver take care of that.
125
     *
126
     * @return bool True on success and false on failure.
127
     *
128
     * @throws InvalidArgumentException Thrown if $values is neither an array nor a Traversable,
129
     *                                  or if any of the $values are not a legal value.
130
     */
131
    public function setMultiple($values, $ttl = null)
132
    {
133
        foreach ($values as $key => $value) {
134
            $this->set($key, $value, $ttl);
135
        }
136
137
        return true;
138
    }
139
140
    /**
141
     * Deletes multiple cache items in a single operation.
142
     *
143
     * @param iterable $keys A list of string-based keys to be deleted.
144
     *
145
     * @return bool True if the items were successfully removed. False if there was an error.
146
     *
147
     * @throws InvalidArgumentException Thrown if $keys is neither an array nor a Traversable,
148
     *                                  or if any of the $keys are not a legal value.
149
     */
150
    public function deleteMultiple($keys)
151
    {
152
        foreach ($keys as $key) {
153
            $this->delete($key);
154
        }
155
156
        return true;
157
    }
158
159
    /**
160
     * Determines whether an item is present in the cache.
161
     *
162
     * NOTE: It is recommended that has() is only to be used for cache warming type purposes
163
     * and not to be used within your live applications operations for get/set, as this method
164
     * is subject to a race condition where your has() will return true and immediately after,
165
     * another script can remove it making the state of your app out of date.
166
     *
167
     * @param string $key The cache item key.
168
     *
169
     * @return bool
170
     *
171
     * @throws InvalidArgumentException Thrown if the $key string is not a legal value.
172
     */
173
    public function has($key)
174
    {
175
        $this->verifyKey($key);
176
        return isset($this->cache[$key]);
177
    }
178
179
    /**
180
     * Converts the given time to live value to a epoch timestamp.
181
     *
182
     * @param mixed $key The cache key to validate.
0 ignored issues
show
Bug introduced by
There is no parameter named $key. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
183
     *
184
     * @return void
185
     *
186
     * @throws InvalidArgumentException Thrown if the $ttl is not null, an integer or \DateInterval.
187
     */
188
    private function getExpires($ttl)
189
    {
190
        if ($ttl === null) {
191
            return time() + 86400;
192
        }
193
194
        if (is_int($ttl)) {
195
            return time() + $ttl;
196
        }
197
198
        if ($ttl instanceof \DateInterval) {
199
            return time() + $ttl->s;
200
        }
201
202
        throw new InvalidArgumentException('$ttl must be null, an integer or \DateInterval instance');
203
    }
204
}
205