Failed Conditions
Pull Request — master (#13)
by Chad
04:24
created

InMemoryCache::deleteMultiple()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
rs 9.9666
c 0
b 0
f 0
cc 2
nc 2
nop 1
1
<?php
2
3
namespace SubjectivePHP\Psr\SimpleCache;
4
5
use ArrayAccess;
6
use ArrayObject;
7
use DateInterval;
8
use DateTime;
9
use Psr\SimpleCache\CacheInterface;
10
11
/**
12
 * A PSR-16 implementation which stores data in an array.
13
 */
14
final class InMemoryCache implements CacheInterface
15
{
16
    use KeyValidatorTrait;
17
    use TTLValidatorTrait;
18
19
    /**
20
     * @var ArrayObject
21
     */
22
    private $cache;
23
24
    /**
25
     * Construct a new instance of InMemoryCache.
26
     *
27
     * @param ArrayAccess $cache Initial cache container.
28
     */
29
    public function __construct(ArrayAccess $cache = null)
30
    {
31
        $this->cache = $cache ?? new ArrayObject();
0 ignored issues
show
Documentation Bug introduced by
$cache ?? new \ArrayObject() is of type object<ArrayAccess>, but the property $cache was declared to be of type object<ArrayObject>. Are you sure that you always receive this specific sub-class here, or does it make sense to add an instanceof check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a given class or a super-class is assigned to a property that is type hinted more strictly.

Either this assignment is in error or an instanceof check should be added for that assignment.

class Alien {}

class Dalek extends Alien {}

class Plot
{
    /** @var  Dalek */
    public $villain;
}

$alien = new Alien();
$plot = new Plot();
if ($alien instanceof Dalek) {
    $plot->villain = $alien;
}
Loading history...
32
    }
33
34
    /**
35
     * Fetches a value from the cache.
36
     *
37
     * @param string $key     The unique key of this item in the cache.
38
     * @param mixed  $default Default value to return if the key does not exist.
39
     *
40
     * @return mixed The value of the item from the cache, or $default in case of cache miss.
41
     *
42
     * @throws InvalidArgumentException Thrown if the $key string is not a legal value.
43
     */
44
    public function get($key, $default = null)//@codingStandardsIgnoreLine Interface does not define type-hints or return
45
    {
46
        $this->validateKey($key);
47
        $cache = $this->cache[$key] ?? null;
48
        if ($cache === null) {
49
            return $default;
50
        }
51
52
        if ($cache['expires'] >= time()) {
53
            return $cache['data'];
54
        }
55
56
        unset($this->cache[$key]);
57
        return $default;
58
    }
59
60
    /**
61
     * Obtains multiple cache items by their unique keys.
62
     *
63
     * @param iterable $keys    A list of keys that can obtained in a single operation.
64
     * @param mixed    $default Default value to return for keys that do not exist.
65
     *
66
     * @return array List of key => value pairs. Cache keys that do not exist or are stale will have $default as value.
67
     *
68
     * @throws InvalidArgumentException Thrown if the $key string is not a legal value.
69
     */
70
    public function getMultiple($keys, $default = null)//@codingStandardsIgnoreLine Interface does not define type-hints or return
71
    {
72
        $result = [];
73
        foreach ($keys as $key) {
74
            $result[$key] = $this->get($key, $default);
75
        }
76
77
        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...
78
    }
79
80
    /**
81
     * Persists data in the cache, uniquely referenced by a key with an optional expiration TTL time.
82
     *
83
     * @param string                    $key   The key of the item to store.
84
     * @param mixed                     $value The value of the item to store, must be serializable.
85
     * @param null|integer|DateInterval $ttl   Optional. The TTL value of this item. If no value is sent and
86
     *                                         the driver supports TTL then the library may set a default value
87
     *                                         for it or let the driver take care of that.
88
     *
89
     * @return boolean True on success and false on failure.
90
     *
91
     * @throws InvalidArgumentException Thrown if the $key string is not a legal value.
92
     */
93
    public function set($key, $value, $ttl = null)//@codingStandardsIgnoreLine Interface does not define type-hints or return
94
    {
95
        $this->validateKey($key);
96
        $this->validateTTL($ttl);
97
        $this->cache[$key] = ['data' => $value, 'expires' => $this->getExpiration($ttl)];
98
        return true;
99
    }
100
101
    /**
102
     * Persists a set of key => value pairs in the cache, with an optional TTL.
103
     *
104
     * @param iterable                  $values A list of key => value pairs for a multiple-set operation.
105
     * @param null|integer|DateInterval $ttl    Optional. The TTL value of this item. If no value is sent and
106
     *                                          the driver supports TTL then the library may set a default value
107
     *                                          for it or let the driver take care of that.
108
     *
109
     * @return boolean True on success and false on failure.
110
     *
111
     * @throws InvalidArgumentException Thrown if $values is neither an array nor a Traversable,
112
     *                                  or if any of the $values are not a legal value.
113
     */
114
    public function setMultiple($values, $ttl = null)//@codingStandardsIgnoreLine Interface does not define type-hints or return
115
    {
116
        $keys = array_keys($values);
117
        $this->validateKeys($keys);
118
        $this->getExpiration($ttl);
119
120
        foreach ($values as $key => $value) {
121
            $this->set($key, $value, $ttl);
122
        }
123
124
        return true;
125
    }
126
127
    /**
128
     * Delete an item from the cache by its unique key.
129
     *
130
     * @param string $key The unique cache key of the item to delete.
131
     *
132
     * @return boolean True if the item was successfully removed. False if there was an error.
133
     *
134
     * @throws InvalidArgumentException Thrown if the $key string is not a legal value.
135
     */
136
    public function delete($key)//@codingStandardsIgnoreLine Interface does not define type-hints or return
137
    {
138
        $this->validateKey($key);
139
        unset($this->cache[$key]);
140
        return true;
141
    }
142
143
    /**
144
     * Deletes multiple cache items in a single operation.
145
     *
146
     * @param iterable $keys A list of string-based keys to be deleted.
147
     *
148
     * @return boolean True if the items were successfully removed. False if there was an error.
149
     *
150
     * @throws InvalidArgumentException Thrown if $keys is neither an array nor a Traversable,
151
     *                                  or if any of the $keys are not a legal value.
152
     */
153
    public function deleteMultiple($keys)//@codingStandardsIgnoreLine Interface does not define type-hints
154
    {
155
        $this->validateKeys($keys);
156
        foreach ($keys as $key) {
157
            unset($this->cache[$key]);
158
        }
159
160
        return true;
161
    }
162
163
    /**
164
     * Wipes clean the entire cache's keys.
165
     *
166
     * @return boolean True on success and false on failure.
167
     */
168
    public function clear()//@codingStandardsIgnoreLine Interface does not define type-hints or return
169
    {
170
        $this->cache = [];
0 ignored issues
show
Documentation Bug introduced by
It seems like array() of type array is incompatible with the declared type object<ArrayObject> of property $cache.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
171
        return true;
172
    }
173
174
    /**
175
     * Determines whether an item is present in the cache.
176
     *
177
     * NOTE: It is recommended that has() is only to be used for cache warming type purposes
178
     * and not to be used within your live applications operations for get/set, as this method
179
     * is subject to a race condition where your has() will return true and immediately after,
180
     * another script can remove it making the state of your app out of date.
181
     *
182
     * @param string $key The cache item key.
183
     *
184
     * @return boolean
185
     *
186
     * @throws InvalidArgumentException Thrown if the $key string is not a legal value.
187
     */
188
    public function has($key) //@codingStandardsIgnoreLine  Interface does not define type-hints
189
    {
190
        $this->validateKey($key);
191
        return $this->get($key, false) !== false;
192
    }
193
194
    /**
195
     * Converts the given time to live value to a DataTime instance;
196
     *
197
     * @param mixed $ttl The time-to-live value to validate.
198
     *
199
     * @return integer
200
     */
201
    private function getExpiration($ttl) : int
202
    {
203
        if ($ttl === null) {
204
            return PHP_INT_MAX;
205
        }
206
207
        if (is_int($ttl)) {
208
            return time() + $ttl;
209
        }
210
211
        return (new DateTime())->add($ttl)->getTimestamp();
212
    }
213
}
214