Failed Conditions
Push — v3.x ( babbd8...d960e5 )
by Chad
02:14
created

src/Cache/ArrayCache.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

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 ArrayCache 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
        $this->verifyValue($value);
63
64
        $this->cache[$key] = [
65
            'response' => $value,
66
            'expires' => $this->getExpires($ttl),
67
        ];
68
69
        return true;
70
    }
71
72
    /**
73
     * Delete an item from the cache by its unique key.
74
     *
75
     * @param string $key The unique cache key of the item to delete.
76
     *
77
     * @return bool True if the item was successfully removed. False if there was an error.
78
     *
79
     * @throws InvalidArgumentException Thrown if the $key string is not a legal value.
80
     */
81
    public function delete($key)
82
    {
83
        $this->verifyKey($key);
84
        unset($this->cache[$key]);
85
        return true;
86
    }
87
88
    /**
89
     * Wipes clean the entire cache's keys.
90
     *
91
     * @return bool True on success and false on failure.
92
     */
93
    public function clear()
94
    {
95
        $this->cache = [];
96
        return true;
97
    }
98
99
    /**
100
     * Obtains multiple cache items by their unique keys.
101
     *
102
     * @param iterable $keys    A list of keys that can obtained in a single operation.
103
     * @param mixed    $default Default value to return for keys that do not exist.
104
     *
105
     * @return iterable A list of key => value pairs. Cache keys that do not exist or are stale will have $default as value.
106
     *
107
     * @throws InvalidArgumentException Thrown if the $key string is not a legal value.
108
     */
109 View Code Duplication
    public function getMultiple($keys, $default = null)
110
    {
111
        $items = [];
112
        foreach ($keys as $key) {
113
            $items[$key] = $this->get($key, $default);
114
        }
115
116
        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...
117
    }
118
119
    /**
120
     * Persists a set of key => value pairs in the cache, with an optional TTL.
121
     *
122
     * @param iterable              $values A list of key => value pairs for a multiple-set operation.
123
     * @param null|int|DateInterval $ttl    Optional. The TTL value of this item. If no value is sent and
124
     *                                      the driver supports TTL then the library may set a default value
125
     *                                      for it or let the driver take care of that.
126
     *
127
     * @return bool True on success and false on failure.
128
     *
129
     * @throws InvalidArgumentException Thrown if $values is neither an array nor a Traversable,
130
     *                                  or if any of the $values are not a legal value.
131
     */
132
    public function setMultiple($values, $ttl = null)
133
    {
134
        foreach ($values as $key => $value) {
135
            $this->set($key, $value, $ttl);
136
        }
137
138
        return true;
139
    }
140
141
    /**
142
     * Deletes multiple cache items in a single operation.
143
     *
144
     * @param iterable $keys A list of string-based keys to be deleted.
145
     *
146
     * @return bool True if the items were successfully removed. False if there was an error.
147
     *
148
     * @throws InvalidArgumentException Thrown if $keys is neither an array nor a Traversable,
149
     *                                  or if any of the $keys are not a legal value.
150
     */
151
    public function deleteMultiple($keys)
152
    {
153
        foreach ($keys as $key) {
154
            $this->delete($key);
155
        }
156
157
        return true;
158
    }
159
160
    /**
161
     * Determines whether an item is present in the cache.
162
     *
163
     * NOTE: It is recommended that has() is only to be used for cache warming type purposes
164
     * and not to be used within your live applications operations for get/set, as this method
165
     * is subject to a race condition where your has() will return true and immediately after,
166
     * another script can remove it making the state of your app out of date.
167
     *
168
     * @param string $key The cache item key.
169
     *
170
     * @return bool
171
     *
172
     * @throws InvalidArgumentException Thrown if the $key string is not a legal value.
173
     */
174
    public function has($key)
175
    {
176
        $this->verifyKey($key);
177
        return isset($this->cache[$key]);
178
    }
179
180
    /**
181
     * Converts the given time to live value to a epoch timestamp.
182
     *
183
     * @param mixed $key The cache key to validate.
184
     *
185
     * @return void
186
     *
187
     * @throws InvalidArgumentException Thrown if the $ttl is not null, an integer or \DateInterval.
188
     */
189
    private function getExpires($ttl)
190
    {
191
        if ($ttl === null) {
192
            return time() + 86400;
193
        }
194
195
        if (is_int($ttl)) {
196
            return time() + $ttl;
197
        }
198
199
        if ($ttl instanceof \DateInterval) {
200
            return time() + $ttl->s;
201
        }
202
203
        throw new InvalidArgumentException('$ttl must be null, an integer or \DateInterval instance');
204
    }
205
}
206