Completed
Push — 2.1 ( fd9384...61dec0 )
by Alexander
08:39
created

DbCache::deleteValue()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 6
cts 6
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 6
nc 1
nop 1
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 37
    public function init()
94
    {
95 37
        parent::init();
96 37
        $this->db = Instance::ensure($this->db, Connection::class);
97 37
    }
98
99
    /**
100
     * {@inheritdoc}
101
     */
102 6
    public function has($key)
103
    {
104 6
        $key = $this->normalizeKey($key);
105
106 6
        $query = new Query();
107 6
        $query->select(['COUNT(*)'])
108 6
            ->from($this->cacheTable)
109 6
            ->where('[[id]] = :id AND ([[expire]] = 0 OR [[expire]] >' . time() . ')', [':id' => $key]);
110 6
        if ($this->db->enableQueryCache) {
111
            // temporarily disable and re-enable query caching
112 6
            $this->db->enableQueryCache = false;
113 6
            $result = $query->createCommand($this->db)->queryScalar();
114 6
            $this->db->enableQueryCache = true;
115
        } else {
116
            $result = $query->createCommand($this->db)->queryScalar();
117
        }
118
119 6
        return $result > 0;
120
    }
121
122
    /**
123
     * {@inheritdoc}
124
     */
125 30
    protected function getValue($key)
126
    {
127 30
        $query = (new Query())
128 30
            ->select(['data'])
129 30
            ->from($this->cacheTable)
130 30
            ->where('[[id]] = :id AND ([[expire]] = 0 OR [[expire]] >' . time() . ')', [':id' => $key]);
131
132 30
        if ($this->db->enableQueryCache) {
133
            // temporarily disable and re-enable query caching
134 30
            $this->db->enableQueryCache = false;
135 30
            $result = $query->createCommand($this->db)->queryScalar();
136 30
            $this->db->enableQueryCache = true;
137 30
            return $result;
138
        }
139
140
        return $query->createCommand($this->db)->queryScalar();
141
    }
142
143
    /**
144
     * {@inheritdoc}
145
     */
146 6
    protected function getValues($keys)
147
    {
148 6
        if (empty($keys)) {
149
            return [];
150
        }
151 6
        $query = (new Query())
152 6
            ->select(['id', 'data'])
153 6
            ->from($this->cacheTable)
154 6
            ->where(['id' => $keys])
155 6
            ->andWhere('([[expire]] = 0 OR [[expire]] > ' . time() . ')');
156
157 6
        if ($this->db->enableQueryCache) {
158 6
            $this->db->enableQueryCache = false;
159 6
            $rows = $query->createCommand($this->db)->queryAll();
160 6
            $this->db->enableQueryCache = true;
161
        } else {
162
            $rows = $query->createCommand($this->db)->queryAll();
163
        }
164
165 6
        $results = array_fill_keys($keys, false);
166 6
        foreach ($rows as $row) {
167 6
            if (is_resource($row['data']) && get_resource_type($row['data']) === 'stream') {
168 3
                $results[$row['id']] = stream_get_contents($row['data']);
169
            } else {
170 6
                $results[$row['id']] = $row['data'];
171
            }
172
        }
173
174 6
        return $results;
175
    }
176
177
    /**
178
     * {@inheritdoc}
179
     */
180
    protected function setValue($key, $value, $ttl)
181
    {
182 32
        $result = $this->db->noCache(function (Connection $db) use ($key, $value, $ttl) {
183 32
            $command = $db->createCommand()
184 32
                ->update($this->cacheTable, [
185 32
                    'expire' => $ttl > 0 ? $ttl + time() : 0,
186 32
                    'data' => [$value, \PDO::PARAM_LOB],
187 32
                ], ['id' => $key]);
188 32
            return $command->execute();
189 32
        });
190
191 32
        if ($result) {
192 2
            $this->gc();
193 2
            return true;
194
        }
195
        
196 32
        return $this->addValue($key, $value, $ttl);
197
    }
198
199
    /**
200
     * Stores a value identified by a key into cache if the cache does not contain this key.
201
     * This is the implementation of the method declared in the parent class.
202
     *
203
     * @param string $key the key identifying the value to be cached
204
     * @param string $value the value to be cached. Other types (if you have disabled [[serializer]]) cannot be saved.
205
     * @param int $duration the number of seconds in which the cached value will expire. 0 means never expire.
206
     * @return bool true if the value is successfully stored into cache, false otherwise
207
     */
208 32
    protected function addValue($key, $value, $duration)
209
    {
210 32
        $this->gc();
211
212
        try {
213 32
            $this->db->noCache(function (Connection $db) use ($key, $value, $duration) {
214 32
                $db->createCommand()
215 32
                    ->insert($this->cacheTable, [
216 32
                        'id' => $key,
217 32
                        'expire' => $duration > 0 ? $duration + time() : 0,
218 32
                        'data' => [$value, \PDO::PARAM_LOB],
219 32
                    ])->execute();
220 32
            });
221
222 32
            return true;
223
        } catch (\Exception $e) {
224
            return false;
225
        }
226
    }
227
228
    /**
229
     * {@inheritdoc}
230
     */
231
    protected function deleteValue($key)
232
    {
233 2
        $this->db->noCache(function (Connection $db) use ($key) {
234 2
            $db->createCommand()
235 2
                ->delete($this->cacheTable, ['id' => $key])
236 2
                ->execute();
237 2
        });
238
239 2
        return true;
240
    }
241
242
    /**
243
     * Removes the expired data values.
244
     * @param bool $force whether to enforce the garbage collection regardless of [[gcProbability]].
245
     * Defaults to false, meaning the actual deletion happens with the probability as specified by [[gcProbability]].
246
     */
247 32
    public function gc($force = false)
248
    {
249 32
        if ($force || mt_rand(0, 1000000) < $this->gcProbability) {
250
            $this->db->createCommand()
251
                ->delete($this->cacheTable, '[[expire]] > 0 AND [[expire]] < ' . time())
252
                ->execute();
253
        }
254 32
    }
255
256
    /**
257
     * {@inheritdoc}
258
     */
259 22
    public function clear()
260
    {
261 22
        $this->db->createCommand()
262 22
            ->delete($this->cacheTable)
263 22
            ->execute();
264
265 22
        return true;
266
    }
267
}
268