Completed
Push — master ( f49eda...d3555b )
by Leandro
11:37 queued 10:16
created

Settings::delete()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 3.0213

Importance

Changes 0
Metric Value
dl 0
loc 20
ccs 13
cts 15
cp 0.8667
rs 9.6
c 0
b 0
f 0
cc 3
nc 4
nop 1
crap 3.0213
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
10
11
class Settings extends Component
12
{
13
    /**
14
     * @event ModelEvent an event that is triggered before inserting a record.
15
     * You may set [[ModelEvent::isValid]] to be `false` to stop the insertion.
16
     */
17
    const EVENT_BEFORE_FIND = 'beforeFind';
18
    /**
19
     * @event ModelEvent an event that is triggered before inserting a record.
20
     * You may set [[ModelEvent::isValid]] to be `false` to stop the insertion.
21
     */
22
    const EVENT_BEFORE_SAVE = 'beforeSave';
23
24
    /**
25
     * @var string Name of the table where configurations will be stored
26
     */
27
    public $tableName = '{{%settings}}';
28
29
    /**
30
     * @var string Name of column where keys will be stored
31
     */
32
    public $keyColumnName = 'key';
33
34
    /**
35
     * @var string Name of column where values will be stored
36
     */
37
    public $valueColumnName = 'value';
38
39
    /**
40
     * @return Connection the DB connection instance
41
     */
42 2
    protected function getDb()
43
    {
44 2
        return Yii::$app->getDb();
45
    }
46
47
    /**
48
     * Whether the configuration exists in the database
49
     * @param string $name configuration name
50
     * @param integer $tenantId The tenant id value
0 ignored issues
show
Bug introduced by
There is no parameter named $tenantId. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
51
     * @return bool
52
     */
53 2
    protected function exists($name)
54
    {
55 2
        $query = $this->createQuery($name);
56 2
        return $query->exists();
57
    }
58
59
    /**
60
     * Returns configuration value from database
61
     * @param string $name configuration name
62
     * @param mixed $defaultValue the default value to be returned when the session variable does not exist.
63
     * @return string value stored in database
64
     */
65 1
    public function get($name, $defaultValue = null)
66
    {
67 1
        $value = null;
0 ignored issues
show
Unused Code introduced by
$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...
68 1
        $query = $this->createQuery($name);
69 1
        $row = $query->one($this->getDb());
70
71 1
        $value = ($row) ? $row[$this->valueColumnName] : null;
72
73 1
        if (is_string($value) && trim($value) == '') {
74
            $value = null;
75
        }
76
77 1
        return ($value !== null) ? $value : $defaultValue;
78
    }
79
80
    /**
81
     * Store configuration value to database
82
     * @param string $name
83
     * @param mixed $value
84
     * @param integer $tenantId The tenant id value
85
     */
86 2
    public function set($name, $value, $tenantId = null)
0 ignored issues
show
Unused Code introduced by
The parameter $tenantId is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
87
    {
88 2
        $db = $this->getDb();
89
90 2
        $event = new SettingsEvent();
91 2
        $this->trigger(self::EVENT_BEFORE_SAVE, $event);
92
93 2
        $columns = array_merge($event->columns, [$this->valueColumnName => $value]);
94 2
        $where = array_merge($event->columns, [$this->keyColumnName => $name]);
95
96 2
        if ($this->exists($name)) {
97 1
            $db->createCommand()
98 1
                ->update($this->tableName, $columns, $where)
99 1
                ->execute();
100 1
        } else  {
101 2
            $values = array_merge([$this->keyColumnName => $name], $columns);
102
103 2
            $db->createCommand()
104 2
                ->insert($this->tableName, $values)
105 2
                ->execute();
106
        }
107 2
    }
108
109
    /**
110
     * Retrieves all configurations stored in database
111
     * @param integer $tenantId
0 ignored issues
show
Bug introduced by
There is no parameter named $tenantId. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
112
     * @return array
113
     */
114 1
    public function all()
115
    {
116 1
        $result = [];
117
118 1
        $query = $this->createQuery()
119 1
            ->addSelect($this->keyColumnName);
120
121 1
        $rows = $query->all($this->getDb());
122
123 1
        foreach ($rows as $row) {
124 1
            $result[$row[$this->keyColumnName]] = $row[$this->valueColumnName];
125 1
        }
126
127 1
        return $result;
128
    }
129
130
    /**
131
     * Store all configuration in database
132
     * @param array $names
133
     */
134 1
    public function save($names)
135
    {
136 1
        foreach ($names as $key => $value) {
137 1
            $this->set($key, $value) ;
138 1
        }
139 1
    }
140
141
    /**
142
     * Deletes specified configurations (or all if none specified) from the parameters table
143
     * @param array|string $names
144
     * @param integer $tenantId
0 ignored issues
show
Bug introduced by
There is no parameter named $tenantId. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
145
     */
146 1
    public function delete($names = [])
147
    {
148 1
        if (is_array($names)) {
149 1
            $where = ['IN', $this->keyColumnName, $names];
150 1
        } else {
151 1
            $where = [$this->keyColumnName => $names];
152
        }
153
154 1
        $event = new SettingsEvent();
155 1
        $this->trigger(self::EVENT_BEFORE_FIND, $event);
156
157 1
        if ($event->columns) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $event->columns of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
158
            $where = array_merge($event->columns, $where);
159
        }
160
161 1
        $this->getDb()
162 1
            ->createCommand()
163 1
            ->delete($this->tableName, $where)
164 1
            ->execute();
165 1
    }
166
167
    /**
168
     * Creates query to find settings value
169
     * @param string $name
170
     * @return \yii\db\Query
171
     */
172 2
    protected function createQuery($name = null)
173
    {
174 2
        $query = (new Query())
175 2
            ->select([$this->valueColumnName])
176 2
            ->from($this->tableName);
177
178 2
        $event = new SettingsEvent();
179 2
        $this->trigger(self::EVENT_BEFORE_FIND, $event);
180
181 2
        if ($event->columns) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $event->columns of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
182 1
            $query->andWhere($event->columns);
183 1
        }
184
185 2
        if ($name) {
0 ignored issues
show
Bug Best Practice introduced by
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...
186 2
            $query->andWhere([$this->keyColumnName => $name]);
187 2
        }
188
189 2
        return $query;
190
    }
191
192
}
193