Completed
Push — master ( 8c6df7...3231a5 )
by Leandro
01:15
created

Settings::get()   B

Complexity

Conditions 6
Paths 9

Size

Total Lines 23

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 6.0163

Importance

Changes 0
Metric Value
dl 0
loc 23
ccs 12
cts 13
cp 0.9231
rs 8.9297
c 0
b 0
f 0
cc 6
nc 9
nop 2
crap 6.0163
1
<?php
2
3
namespace Soluto\Settings;
4
5
use Yii;
6
use yii\base\Component;
7
use yii\db\Connection;
8
use yii\db\Query;
9
use yii\base\Event;
10
11
class Settings extends Component
12
{
13
    /**
14
     * @event SettingsEvent an event that is triggered before execute command.
15
     */
16
    const EVENT_BEFORE_EXECUTE = 'beforeExecute';
17
18
    /*
19
     * @var array The settings cache
20
     */
21
    private $_data = [];
22
23
    /**
24
     * @var string Name of the table where configurations will be stored
25
     */
26
    public $tableName = '{{%setting}}';
27
28
    /**
29
     * @var string Name of column where keys will be stored
30
     */
31
    public $keyColumnName = 'key';
32
33
    /**
34
     * @var string Name of column where values will be stored
35
     */
36
    public $valueColumnName = 'value';
37
38
    /**
39
     * @return Connection the DB connection instance
40
     */
41 2
    protected function getDb()
42
    {
43 2
        return Yii::$app->getDb();
44
    }
45
46
    /**
47
     * Whether the setting exists in the database
48
     * @param string $name the setting name
49
     * @return bool
50
     */
51 2
    protected function exists($name)
52
    {
53 2
        if (isset($this->_data[$name])) {
54 1
            return true;
55
        }
56
57 2
        $query = $this->createQuery($name);
58 2
        return $query->exists();
59
    }
60
61
    /**
62
     * Returns setting value from database
63
     * @param string $name setting name
64
     * @return mixed $defaultValue
65
     */
66 1
    public function get($name, $defaultValue = null)
67
    {
68 1
        if (isset($this->_data[$name])) {
69 1
            return $this->_data[$name];
70
        }
71
72 1
        $value = null;
0 ignored issues
show
Unused Code introduced by leandrogehlen
$value is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
73 1
        $query = $this->createQuery($name);
74 1
        $row = $query->one($this->getDb());
75
76 1
        $value = ($row) ? $row[$this->valueColumnName] : null;
77
78 1
        if (is_string($value) && trim($value) == '') {
79
            $value = null;
80
        }
81
82 1
        if ($value === null) {
83 1
            $value = $defaultValue;
84
        }
85
86 1
        $this->_data[$name] = $value;
87 1
        return $value;
88
    }
89
90
    /**
91
     * Store setting value to database
92
     * @param string $name
93
     * @param mixed $value
94
     */
95 2
    public function set($name, $value)
96
    {
97 2
        $db = $this->getDb();
98 2
        $values = [$this->valueColumnName => $value];
99 2
        $where = [$this->keyColumnName => $name];
100
101 2
        $event = $this->beforeExecute();
102 2
        if ($event->data) {
103 1
            $values = array_merge($event->data, $values);
104 1
            $where = array_merge($event->data, $where);
105
        }
106
107 2
        if ($this->exists($name)) {
108 1
            $db->createCommand()
109 1
                ->update($this->tableName, $values, $where)
110 1
                ->execute();
111
        } else  {
112 2
            $values = array_merge($values, $where);
113
114 2
            $db->createCommand()
115 2
                ->insert($this->tableName, $values)
116 2
                ->execute();
117
        }
118
119 2
        $this->_data[$name] = $value;
120 2
    }
121
122
    /**
123
     * Retrieves all setting stored in database
124
     * @return array
125
     */
126 1
    public function all()
127
    {
128 1
        $result = [];
129
130 1
        $query = $this->createQuery()
131 1
            ->addSelect($this->keyColumnName);
132
133 1
        $rows = $query->all($this->getDb());
134
135 1
        foreach ($rows as $row) {
136 1
            $value = $row[$this->valueColumnName];
137 1
            $name = $row[$this->keyColumnName];
138
139 1
            $result[$name] = $value;
140 1
            $this->_data[$name] = $value;
141
        }
142
143 1
        return $result;
144
    }
145
146
    /**
147
     * Store all settings in database
148
     * @param array $names
149
     */
150 1
    public function save($names)
151
    {
152 1
        foreach ($names as $key => $value) {
153 1
            $this->set($key, $value) ;
154
        }
155 1
    }
156
157
    /**
158
     * Remove specified setting
159
     * @param array|string $name
160
     */
161 1
    public function remove($name)
162
    {
163 1
        $where = [$this->keyColumnName => $name];
164
165 1
        $event = $this->beforeExecute();
166 1
        if ($event->data) {
167
            $where = array_merge($event->data, $where);
168
        }
169
170 1
        $this->getDb()
171 1
            ->createCommand()
172 1
            ->delete($this->tableName, $where)
173 1
            ->execute();
174
175 1
        unset($this->_data[$name]);
176 1
    }
177
178
    /**
179
     * Removes all settings
180
     */
181 1
    public function removeAll()
182
    {
183 1
        $event = $this->beforeExecute();
184 1
        $where = $event->data ? $event->data : '';
185
186 1
        $this->getDb()
187 1
            ->createCommand()
188 1
            ->delete($this->tableName, $where)
189 1
            ->execute();
190
191 1
        $this->_data[] = [];
192 1
    }
193
194
    /**
195
     * Creates query to find settings value
196
     * @param string $name
197
     * @return \yii\db\Query
198
     */
199 2
    protected function createQuery($name = null)
200
    {
201 2
        $query = (new Query())
202 2
            ->select([$this->valueColumnName])
203 2
            ->from($this->tableName);
204
205 2
        $event = $this->beforeExecute();
206
207 2
        if ($event->data) {
208 1
            $query->andWhere($event->data);
209
        }
210
211 2
        if ($name) {
0 ignored issues
show
Bug Best Practice introduced by leandrogehlen
The expression $name of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
212 2
            $query->andWhere([$this->keyColumnName => $name]);
213
        }
214
215 2
        return $query;
216
    }
217
218
    /**
219
     * This method is called at the before execute db command
220
     * @return yii\base\Event
221
     */
222 2
    protected function beforeExecute()
223
    {
224 2
        $event = new Event();
225 2
        $this->trigger(self::EVENT_BEFORE_EXECUTE, $event);
226 2
        return $event;
227
    }
228
229
}
230