Completed
Push — 2.1 ( ba7352...41aa5d )
by Dmitry
21:34 queued 05:31
created

DbCache::has()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 19
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 2.0023

Importance

Changes 0
Metric Value
dl 0
loc 19
ccs 11
cts 12
cp 0.9167
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 13
nc 2
nop 1
crap 2.0023
1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\caching;
9
10
use Yii;
11
use yii\base\InvalidConfigException;
12
use yii\db\Connection;
13
use yii\db\PdoValue;
14
use yii\db\Query;
15
use yii\di\Instance;
16
17
/**
18
 * DbCache implements a cache application component by storing cached data in a database.
19
 *
20
 * By default, DbCache stores session data in a DB table named 'cache'. This table
21
 * must be pre-created. The table name can be changed by setting [[cacheTable]].
22
 *
23
 * Please refer to [[\Psr\SimpleCache\CacheInterface]] for common cache operations that are supported by DbCache.
24
 *
25
 * The following example shows how you can configure the application to use DbCache:
26
 *
27
 * ```php
28
 * return [
29
 *     'components' => [
30
 *         'cache' => [
31
 *             'class' => yii\caching\Cache:class,
32
 *             'handler' => [
33
 *                 'class' => yii\caching\DbCache::class,
34
 *                 // 'db' => 'mydb',
35
 *                 // 'cacheTable' => 'my_cache',
36
 *             ],
37
 *         ],
38
 *         // ...
39
 *     ],
40
 *     // ...
41
 * ];
42
 * ```
43
 *
44
 * For more details and usage information on Cache, see the [guide article on caching](guide:caching-overview).
45
 *
46
 * @author Qiang Xue <[email protected]>
47
 * @since 2.0
48
 */
49
class DbCache extends SimpleCache
50
{
51
    /**
52
     * @var Connection|array|string the DB connection object or the application component ID of the DB connection.
53
     * After the DbCache object is created, if you want to change this property, you should only assign it
54
     * with a DB connection object.
55
     * Starting from version 2.0.2, this can also be a configuration array for creating the object.
56
     */
57
    public $db = 'db';
58
    /**
59
     * @var string name of the DB table to store cache content.
60
     * The table should be pre-created as follows:
61
     *
62
     * ```php
63
     * CREATE TABLE cache (
64
     *     id char(128) NOT NULL PRIMARY KEY,
65
     *     expire int(11),
66
     *     data BLOB
67
     * );
68
     * ```
69
     *
70
     * where 'BLOB' refers to the BLOB-type of your preferred DBMS. Below are the BLOB type
71
     * that can be used for some popular DBMS:
72
     *
73
     * - MySQL: LONGBLOB
74
     * - PostgreSQL: BYTEA
75
     * - MSSQL: BLOB
76
     *
77
     * When using DbCache in a production server, we recommend you create a DB index for the 'expire'
78
     * column in the cache table to improve the performance.
79
     */
80
    public $cacheTable = '{{%cache}}';
81
    /**
82
     * @var int the probability (parts per million) that garbage collection (GC) should be performed
83
     * when storing a piece of data in the cache. Defaults to 100, meaning 0.01% chance.
84
     * This number should be between 0 and 1000000. A value 0 meaning no GC will be performed at all.
85
     */
86
    public $gcProbability = 100;
87
88
89
    /**
90
     * Initializes the DbCache component.
91
     * This method will initialize the [[db]] property to make sure it refers to a valid DB connection.
92
     * @throws InvalidConfigException if [[db]] is invalid.
93
     */
94 37
    public function init()
95
    {
96 37
        parent::init();
97 37
        $this->db = Instance::ensure($this->db, Connection::class);
98 37
    }
99
100
    /**
101
     * {@inheritdoc}
102
     */
103 6
    public function has($key)
104
    {
105 6
        $key = $this->normalizeKey($key);
106
107 6
        $query = new Query();
108 6
        $query->select(['COUNT(*)'])
109 6
            ->from($this->cacheTable)
110 6
            ->where('[[id]] = :id AND ([[expire]] = 0 OR [[expire]] >' . time() . ')', [':id' => $key]);
111 6
        if ($this->db->enableQueryCache) {
112
            // temporarily disable and re-enable query caching
113 6
            $this->db->enableQueryCache = false;
114 6
            $result = $query->createCommand($this->db)->queryScalar();
115 6
            $this->db->enableQueryCache = true;
116
        } else {
117
            $result = $query->createCommand($this->db)->queryScalar();
118
        }
119
120 6
        return $result > 0;
121
    }
122
123
    /**
124
     * {@inheritdoc}
125
     */
126 30
    protected function getValue($key)
127
    {
128 30
        $query = (new Query())
129 30
            ->select(['data'])
130 30
            ->from($this->cacheTable)
131 30
            ->where('[[id]] = :id AND ([[expire]] = 0 OR [[expire]] >' . time() . ')', [':id' => $key]);
132
133 30
        if ($this->db->enableQueryCache) {
134
            // temporarily disable and re-enable query caching
135 30
            $this->db->enableQueryCache = false;
136 30
            $result = $query->createCommand($this->db)->queryScalar();
137 30
            $this->db->enableQueryCache = true;
138
139 30
            return $result;
140
        }
141
142
        return $query->createCommand($this->db)->queryScalar();
143
    }
144
145
    /**
146
     * {@inheritdoc}
147
     */
148 6
    protected function getValues($keys)
149
    {
150 6
        if (empty($keys)) {
151
            return [];
152
        }
153 6
        $query = (new Query())
154 6
            ->select(['id', 'data'])
155 6
            ->from($this->cacheTable)
156 6
            ->where(['id' => $keys])
157 6
            ->andWhere('([[expire]] = 0 OR [[expire]] > ' . time() . ')');
158
159 6
        if ($this->db->enableQueryCache) {
160 6
            $this->db->enableQueryCache = false;
161 6
            $rows = $query->createCommand($this->db)->queryAll();
162 6
            $this->db->enableQueryCache = true;
163
        } else {
164
            $rows = $query->createCommand($this->db)->queryAll();
165
        }
166
167 6
        $results = array_fill_keys($keys, false);
168 6
        foreach ($rows as $row) {
169 6
            if (is_resource($row['data']) && get_resource_type($row['data']) === 'stream') {
170 3
                $results[$row['id']] = stream_get_contents($row['data']);
171
            } else {
172 6
                $results[$row['id']] = $row['data'];
173
            }
174
        }
175
176 6
        return $results;
177
    }
178
179
    /**
180
     * {@inheritdoc}
181
     */
182
    protected function setValue($key, $value, $ttl)
183
    {
184 32
        $result = $this->db->noCache(function (Connection $db) use ($key, $value, $ttl) {
185 32
            $command = $db->createCommand()
186 32
                ->update($this->cacheTable, [
187 32
                    'expire' => $ttl > 0 ? $ttl + time() : 0,
188 32
                    'data' => new PdoValue($value, \PDO::PARAM_LOB),
189 32
                ], ['id' => $key]);
190 32
            return $command->execute();
191 32
        });
192
193 32
        if ($result) {
194 2
            $this->gc();
195
196 2
            return true;
197
        }
198
        
199 32
        return $this->addValue($key, $value, $ttl);
200
    }
201
202
    /**
203
     * Stores a value identified by a key into cache if the cache does not contain this key.
204
     * This is the implementation of the method declared in the parent class.
205
     *
206
     * @param string $key the key identifying the value to be cached
207
     * @param string $value the value to be cached. Other types (if you have disabled [[serializer]]) cannot be saved.
208
     * @param int $duration the number of seconds in which the cached value will expire. 0 means never expire.
209
     * @return bool true if the value is successfully stored into cache, false otherwise
210
     */
211 32
    protected function addValue($key, $value, $duration)
212
    {
213 32
        $this->gc();
214
215
        try {
216 32
            $this->db->noCache(function (Connection $db) use ($key, $value, $duration) {
217 32
                $db->createCommand()
218 32
                    ->insert($this->cacheTable, [
219 32
                        'id' => $key,
220 32
                        'expire' => $duration > 0 ? $duration + time() : 0,
221 32
                        'data' => new PdoValue($value, \PDO::PARAM_LOB),
222 32
                    ])->execute();
223 32
            });
224
225 32
            return true;
226
        } catch (\Exception $e) {
227
            return false;
228
        }
229
    }
230
231
    /**
232
     * {@inheritdoc}
233
     */
234
    protected function deleteValue($key)
235
    {
236 2
        $this->db->noCache(function (Connection $db) use ($key) {
237 2
            $db->createCommand()
238 2
                ->delete($this->cacheTable, ['id' => $key])
239 2
                ->execute();
240 2
        });
241
242 2
        return true;
243
    }
244
245
    /**
246
     * Removes the expired data values.
247
     * @param bool $force whether to enforce the garbage collection regardless of [[gcProbability]].
248
     * Defaults to false, meaning the actual deletion happens with the probability as specified by [[gcProbability]].
249
     */
250 32
    public function gc($force = false)
251
    {
252 32
        if ($force || mt_rand(0, 1000000) < $this->gcProbability) {
253
            $this->db->createCommand()
254
                ->delete($this->cacheTable, '[[expire]] > 0 AND [[expire]] < ' . time())
255
                ->execute();
256
        }
257 32
    }
258
259
    /**
260
     * {@inheritdoc}
261
     */
262 22
    public function clear()
263
    {
264 22
        $this->db->createCommand()
265 22
            ->delete($this->cacheTable)
266 22
            ->execute();
267
268 22
        return true;
269
    }
270
}
271