Failed Conditions
Pull Request — master (#9)
by Chad
01:27
created

MongoCache::set()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

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

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
219
    }
220
221
    /**
222
     * Upserts a PSR-7 response in the cache.
223
     *
224
     * @param string      $key     The key of the response to store.
225
     * @param array       $value   The data to store.
226
     * @param UTCDateTime $expires The expire date of the cache item.
227
     *
228
     * @return boolean
229
     */
230
    private function updateCache(string $key, array $value, UTCDateTime $expires) : bool
231
    {
232
        $document = ['_id' => $key, 'expires' => $expires]  + $value;
233
        try {
234
            $this->collection->updateOne(['_id' => $key], ['$set' => $document], ['upsert' => true]);
235
            return true;
236
        } catch (\Exception $e) {
237
            return false;
238
        }
239
    }
240
241
    /**
242
     * Converts the given time to live value to a UTCDateTime instance;
243
     *
244
     * @param mixed $ttl The time-to-live value to validate.
245
     *
246
     * @return UTCDateTime
247
     */
248
    private function getExpires($ttl) : UTCDateTime
249
    {
250
        $this->validateTTL($ttl);
251
252
        $ttl = $ttl ?: 86400;
253
254
        if ($ttl instanceof \DateInterval) {
255
            return new UTCDateTime((new \DateTime('now'))->add($ttl)->getTimestamp() * 1000);
256
        }
257
258
        return new UTCDateTime((time() + $ttl) * 1000);
259
    }
260
}
261