forked from yii2tech/config
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStorageDb.php
92 lines (84 loc) · 2.11 KB
/
StorageDb.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
<?php
/**
* @link https://github.com/yii2tech
* @copyright Copyright (c) 2015 Yii2tech
* @license [New BSD License](http://www.opensource.org/licenses/bsd-license.php)
*/
namespace yii2tech\config;
use Yii;
use yii\db\Connection;
use yii\db\Query;
use yii\di\Instance;
/**
* StorageDb represents the configuration storage based on database table.
* Example migration for such table:
*
* ```php
* $tableName = 'AppConfig';
* $columns = [
* 'id' => 'string',
* 'value' => 'text',
* 'PRIMARY KEY(id)',
* ];
* $this->createTable($tableName, $columns);
* ```
*
* @author Paul Klimov <[email protected]>
* @since 1.0
*/
class StorageDb extends Storage
{
/**
* @var Connection|array|string the DB connection object or the application component ID of the DB connection.
* After the StorageDb object is created, if you want to change this property, you should only assign it
* with a DB connection object.
*/
public $db = 'db';
/**
* @var string name of the table, which should store values.
*/
public $table = 'AppConfig';
/**
* @inheritdoc
*/
public function init()
{
parent::init();
$this->db = Instance::ensure($this->db, Connection::className());
}
/**
* @inheritdoc
*/
public function save(array $values)
{
$this->clear();
$data = [];
foreach ($values as $id => $value) {
$data[] = [$id, $value];
}
$command = $this->db->createCommand()->batchInsert($this->table, ['id', 'value'], $data);
$insertedRowsCount = $command->execute();
return (count($values) === $insertedRowsCount);
}
/**
* @inheritdoc
*/
public function get()
{
$query = new Query();
$rows = $query->from($this->table)->all();
$values = [];
foreach ($rows as $row) {
$values[$row['id']] = $row['value'];
}
return $values;
}
/**
* @inheritdoc
*/
public function clear()
{
$this->db->createCommand()->delete($this->table)->execute();
return true;
}
}