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

MongoCache::delete()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

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