Completed
Push — master ( 807d05...dfc103 )
by Chad
9s
created

InMemoryCache::setMultiple()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

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