forked from callmez/yii2-config
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DbConfig.php
137 lines (122 loc) · 2.94 KB
/
DbConfig.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
<?php
namespace weyii\config;
use yii\db\Query;
use yii\di\Instance;
use yii\db\Connection;
/**
* Class DbConfig
* @package weyii\config
*/
class DbConfig extends Config
{
/**
* @var Connection|array|string the DB connection object or the application component ID of the DB connection.
*/
public $db = 'db';
/**
* The configuration data tablename
* @var string
*/
public $configTable = '{{%config}}';
public function init()
{
$this->db = Instance::ensure($this->db, Connection::className());
parent::init();
// Note the default configuration data value will not store to database.
$this->data = array_merge($this->loadData(), $this->data);
}
/**
* @inheritdoc
*/
public function set($key, $value = null)
{
if (!is_array($key)) {
$rootKey = $this->getRootKey($key);
$hasRootKey = $this->has($rootKey);
} else {
$rootKey = false;
}
parent::set($key, $value);
if ($rootKey) {
if ($hasRootKey) {
$this->updateData($rootKey);
} else {
$this->insertData($rootKey);
}
}
}
/**
* @inheritdoc
*/
public function delete($key)
{
parent::delete($key);
$rootKey = $this->getRootKey($key);
if (strpos($key, '.') === false) {
$this->deleteData($rootKey);
} else {
$this->updateData($rootKey);
}
}
/**
* @inheritdoc
*/
protected function loadData()
{
$query = (new Query)->from($this->configTable);
$data = [];
foreach ($query->all($this->db) as $row) {
$data[$row['name']] = unserialize($row['value']);
}
return $data;
}
/**
* Get configuration root key.
*
* @param $key
* @return mixed
*/
protected function getRootKey($key)
{
return explode('.', $key)[0];
}
/**
* Insert new configuration value.
*
* @param $rootKey
*/
protected function insertData($rootKey)
{
$this->db
->createCommand()
->insert($this->configTable, [
'name' => $rootKey,
'value' => serialize($this->get($rootKey))
])
->execute();
}
/**
* Update new configuration value.
*
* @param $rootKey
*/
protected function updateData($rootKey)
{
$this->db
->createCommand()
->update($this->configTable, ['value' => serialize($this->get($rootKey))], ['name' => $rootKey])
->execute();
}
/**
* Delete configuration value.
*
* @param $rootKey
*/
protected function deleteData($rootKey)
{
$this->db
->createCommand()
->delete($this->configTable, ['name' => $rootKey])
->execute();
}
}