Completed
Push — master ( 9e6a90...fdffae )
by Loban
03:15
created

DbStorage::setValue()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 2.004

Importance

Changes 0
Metric Value
dl 0
loc 16
ccs 9
cts 10
cp 0.9
rs 9.7333
c 0
b 0
f 0
cc 2
nc 2
nop 2
crap 2.004
1
<?php
2
/**
3
 * @link https://github.com/LAV45/yii2-settings
4
 * @copyright Copyright (c) 2016 LAV45
5
 * @author Alexey Loban <[email protected]>
6
 * @license http://opensource.org/licenses/BSD-3-Clause
7
 */
8
9
namespace lav45\settings\storage;
10
11
use yii\db\Query;
12
use yii\db\Connection;
13
use yii\di\Instance;
14
use yii\base\BaseObject;
15
16
/**
17
 * Class DbStorage
18
 * @package lav45\settings\storage
19
 */
20
class DbStorage extends BaseObject implements StorageInterface
21
{
22
    /**
23
     * @var Connection|array|string
24
     */
25
    public $db = 'db';
26
    /**
27
     * @var string
28
     */
29
    public $tableName = '{{%settings}}';
30
31
    /**
32
     * Initializes the application component.
33
     */
34 1
    public function init()
35
    {
36 1
        parent::init();
37 1
        $this->db = Instance::ensure($this->db, Connection::class);
38 1
    }
39
40
    /**
41
     * @param string $key
42
     * @return false|null|string
43
     */
44 1
    public function getValue($key)
45
    {
46 1
        return (new Query())
47 1
            ->select(['data'])
48 1
            ->from($this->tableName)
49 1
            ->where(['id' => $key])
50 1
            ->limit(1)
51 1
            ->createCommand($this->db)
52 1
            ->queryScalar();
53
    }
54
55
    /**
56
     * @param string $key
57
     * @param string $value
58
     * @return bool
59
     */
60 1
    public function setValue($key, $value)
61
    {
62 1
        $exists = (new Query())
63 1
            ->from($this->tableName)
64 1
            ->where(['id' => $key])
65 1
            ->exists($this->db);
66
67 1
        $query = (new Query())->createCommand($this->db);
68
69 1
        if ($exists) {
70
            $result = $query->update($this->tableName, ['data' => $value], ['id' => $key])->execute();
71
        } else {
72 1
            $result = $query->insert($this->tableName, ['id' => $key, 'data' => $value])->execute();
73
        }
74 1
        return $result > 0;
75
    }
76
77
    /**
78
     * @param string $key
79
     * @return bool
80
     */
81 1
    public function deleteValue($key)
82
    {
83 1
        $result = (new Query())->createCommand($this->db)
84 1
            ->delete($this->tableName, ['id' => $key])
85 1
            ->execute();
86
87 1
        return $result > 0;
88
    }
89
}
90