Completed
Pull Request — master (#221)
by Andreas
03:46
created

MongoDBCache   A

Complexity

Total Complexity 23

Size/Duplication

Total Lines 182
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 92.86%

Importance

Changes 0
Metric Value
wmc 23
lcom 1
cbo 1
dl 0
loc 182
ccs 52
cts 56
cp 0.9286
rs 10
c 0
b 0
f 0

9 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A doFetch() 0 16 3
A doContains() 0 16 3
A doSave() 0 17 4
A doDelete() 0 6 2
A doFlush() 0 7 2
A doGetStats() 0 20 3
A isExpired() 0 6 3
A createExpirationIndex() 0 9 2
1
<?php
2
/*
3
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
4
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
5
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
13
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
14
 *
15
 * This software consists of voluntary contributions made by many individuals
16
 * and is licensed under the MIT license. For more information, see
17
 * <http://www.doctrine-project.org>.
18
 */
19
20
namespace Doctrine\Common\Cache;
21
22
use MongoBinData;
23
use MongoCollection;
24
use MongoCursorException;
25
use MongoDate;
26
27
/**
28
 * MongoDB cache provider.
29
 *
30
 * @since  1.1
31
 * @author Jeremy Mikola <[email protected]>
32
 */
33
class MongoDBCache extends CacheProvider
34
{
35
    /**
36
     * The data field will store the serialized PHP value.
37
     */
38
    const DATA_FIELD = 'd';
39
40
    /**
41
     * The expiration field will store a MongoDate value indicating when the
42
     * cache entry should expire.
43
     *
44
     * With MongoDB 2.2+, entries can be automatically deleted by MongoDB by
45
     * indexing this field with the "expireAfterSeconds" option equal to zero.
46
     * This will direct MongoDB to regularly query for and delete any entries
47
     * whose date is older than the current time. Entries without a date value
48
     * in this field will be ignored.
49
     *
50
     * The cache provider will also check dates on its own, in case expired
51
     * entries are fetched before MongoDB's TTLMonitor pass can expire them.
52
     *
53
     * @see http://docs.mongodb.org/manual/tutorial/expire-data/
54
     */
55
    const EXPIRATION_FIELD = 'e';
56
57
    /**
58
     * @var MongoCollection
59
     */
60
    private $collection;
61
62
    /**
63
     * @var bool
64
     */
65
    private $expirationIndexCreated = false;
66
67
    /**
68
     * Constructor.
69
     *
70
     * This provider will default to the write concern and read preference
71
     * options set on the MongoCollection instance (or inherited from MongoDB or
72
     * MongoClient). Using an unacknowledged write concern (< 1) may make the
73
     * return values of delete() and save() unreliable. Reading from secondaries
74
     * may make contain() and fetch() unreliable.
75
     *
76
     * @see http://www.php.net/manual/en/mongo.readpreferences.php
77
     * @see http://www.php.net/manual/en/mongo.writeconcerns.php
78
     * @param MongoCollection $collection
79
     */
80 78
    public function __construct(MongoCollection $collection)
81
    {
82 78
        $this->collection = $collection;
83 78
    }
84
85
    /**
86
     * {@inheritdoc}
87
     */
88 76
    protected function doFetch($id)
89
    {
90 76
        $document = $this->collection->findOne(['_id' => $id], [self::DATA_FIELD, self::EXPIRATION_FIELD]);
91
92 76
        if ($document === null) {
93 76
            return false;
94
        }
95
96 64
        if ($this->isExpired($document)) {
97
            $this->createExpirationIndex();
98
            $this->doDelete($id);
99
            return false;
100
        }
101
102 64
        return unserialize($document[self::DATA_FIELD]->bin);
103
    }
104
105
    /**
106
     * {@inheritdoc}
107
     */
108 72
    protected function doContains($id)
109
    {
110 72
        $document = $this->collection->findOne(['_id' => $id], [self::EXPIRATION_FIELD]);
111
112 72
        if ($document === null) {
113 52
            return false;
114
        }
115
116 68
        if ($this->isExpired($document)) {
117 1
            $this->createExpirationIndex();
118 1
            $this->doDelete($id);
119 1
            return false;
120
        }
121
122 68
        return true;
123
    }
124
125
    /**
126
     * {@inheritdoc}
127
     */
128 74
    protected function doSave($id, $data, $lifeTime = 0)
129
    {
130
        try {
131 74
            $result = $this->collection->update(
132 74
                ['_id' => $id],
133 74
                ['$set' => [
134 74
                    self::EXPIRATION_FIELD => ($lifeTime > 0 ? new MongoDate(time() + $lifeTime) : null),
135 74
                    self::DATA_FIELD => new MongoBinData(serialize($data), MongoBinData::BYTE_ARRAY),
136
                ]],
137 74
                ['upsert' => true, 'multiple' => false]
138
            );
139 1
        } catch (MongoCursorException $e) {
140 1
            return false;
141
        }
142
143 73
        return isset($result['ok']) ? $result['ok'] == 1 : true;
144
    }
145
146
    /**
147
     * {@inheritdoc}
148
     */
149 46
    protected function doDelete($id)
150
    {
151 46
        $result = $this->collection->remove(['_id' => $id]);
152
153 46
        return isset($result['ok']) ? $result['ok'] == 1 : true;
154
    }
155
156
    /**
157
     * {@inheritdoc}
158
     */
159 2
    protected function doFlush()
160
    {
161
        // Use remove() in lieu of drop() to maintain any collection indexes
162 2
        $result = $this->collection->remove();
163
164 2
        return isset($result['ok']) ? $result['ok'] == 1 : true;
165
    }
166
167
    /**
168
     * {@inheritdoc}
169
     */
170 1
    protected function doGetStats()
171
    {
172 1
        $serverStatus = $this->collection->db->command([
173 1
            'serverStatus' => 1,
174
            'locks' => 0,
175
            'metrics' => 0,
176
            'recordStats' => 0,
177
            'repl' => 0,
178
        ]);
179
180 1
        $collStats = $this->collection->db->command(['collStats' => 1]);
181
182
        return [
183 1
            Cache::STATS_HITS => null,
184 1
            Cache::STATS_MISSES => null,
185 1
            Cache::STATS_UPTIME => (isset($serverStatus['uptime']) ? (int) $serverStatus['uptime'] : null),
186 1
            Cache::STATS_MEMORY_USAGE => (isset($collStats['size']) ? (int) $collStats['size'] : null),
187 1
            Cache::STATS_MEMORY_AVAILABLE  => null,
188
        ];
189
    }
190
191
    /**
192
     * Check if the document is expired.
193
     *
194
     * @param array $document
195
     *
196
     * @return bool
197
     */
198 69
    private function isExpired(array $document) : bool
199
    {
200 69
        return isset($document[self::EXPIRATION_FIELD]) &&
201 2
            $document[self::EXPIRATION_FIELD] instanceof MongoDate &&
202 69
            $document[self::EXPIRATION_FIELD]->sec < time();
203
    }
204
205 1
    private function createExpirationIndex(): void
206
    {
207 1
        if ($this->expirationIndexCreated) {
208
            return;
209
        }
210
211 1
        $this->expirationIndexCreated = true;
212 1
        $this->collection->createIndex([self::EXPIRATION_FIELD => 1], ['background' => true, 'expireAfterSeconds' => 0]);
213 1
    }
214
}
215