Passed
Push — 2.2 ( 203952...0294cf )
by Paweł
02:05 queued 20s
created

DbDependency::generateDependencyData()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 10
nc 3
nop 1
dl 0
loc 18
ccs 10
cts 10
cp 1
crap 3
rs 9.9332
c 0
b 0
f 0
1
<?php
2
/**
3
 * @link https://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license https://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\di\Instance;
14
15
/**
16
 * DbDependency represents a dependency based on the query result of a SQL statement.
17
 *
18
 * If the query result changes, the dependency is considered as changed.
19
 * The query is specified via the [[sql]] property.
20
 *
21
 * For more details and usage information on Cache, see the [guide article on caching](guide:caching-overview).
22
 *
23
 * @author Qiang Xue <[email protected]>
24
 * @since 2.0
25
 */
26
class DbDependency extends Dependency
27
{
28
    /**
29
     * @var string the application component ID of the DB connection.
30
     */
31
    public $db = 'db';
32
    /**
33
     * @var string the SQL query whose result is used to determine if the dependency has been changed.
34
     * Only the first row of the query result will be used.
35
     */
36
    public $sql;
37
    /**
38
     * @var array the parameters (name => value) to be bound to the SQL statement specified by [[sql]].
39
     */
40
    public $params = [];
41
42
43
    /**
44
     * Generates the data needed to determine if dependency has been changed.
45
     * This method returns the value of the global state.
46
     * @param CacheInterface $cache the cache component that is currently evaluating this dependency
47
     * @return mixed the data needed to determine if dependency has been changed.
48
     * @throws InvalidConfigException if [[db]] is not a valid application component ID
49
     */
50 3
    protected function generateDependencyData($cache)
51
    {
52
        /* @var $db Connection */
53 3
        $db = Instance::ensure($this->db, Connection::class);
54 3
        if ($this->sql === null) {
55 1
            throw new InvalidConfigException('DbDependency::sql must be set.');
56
        }
57
58 2
        if ($db->enableQueryCache) {
59
            // temporarily disable and re-enable query caching
60 1
            $db->enableQueryCache = false;
61 1
            $result = $db->createCommand($this->sql, $this->params)->queryOne();
62 1
            $db->enableQueryCache = true;
63
        } else {
64 1
            $result = $db->createCommand($this->sql, $this->params)->queryOne();
65
        }
66
67 2
        return $result;
68
    }
69
}
70