Completed
Push — 2.1 ( 497a07...c421a1 )
by
unknown
11:23
created

DbCache::init()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

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