Completed
Push — master ( 366f5a...9cc24d )
by Alex
06:09
created

BaseSetting::getValueType()   C

Complexity

Conditions 12
Paths 12

Size

Total Lines 46

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 24
CRAP Score 12.0654

Importance

Changes 0
Metric Value
dl 0
loc 46
ccs 24
cts 26
cp 0.9231
rs 6.9666
c 0
b 0
f 0
cc 12
nc 12
nop 1
crap 12.0654

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * @link http://phe.me
4
 * @copyright Copyright (c) 2014 Pheme
5
 * @license MIT http://opensource.org/licenses/MIT
6
 */
7
8
namespace pheme\settings\models;
9
10
use Yii;
11
use yii\base\InvalidArgumentException;
12
use yii\helpers\Json;
13
use yii\db\ActiveRecord;
14
use yii\helpers\ArrayHelper;
15
use yii\behaviors\TimestampBehavior;
16
17
/**
18
 * This is the model class for table "settings".
19
 *
20
 * @property integer $id
21
 * @property string $type
22
 * @property string $section
23
 * @property string $key
24
 * @property string $value
25
 * @property boolean $active
26
 * @property string $created
27
 * @property string $modified
28
 *
29
 * @author Aris Karageorgos <[email protected]>
30
 */
31
class BaseSetting extends ActiveRecord implements SettingInterface
32
{
33
    /**
34
     * @inheritdoc
35
     */
36 31
    public static function tableName()
37
    {
38 31
        return '{{%settings}}';
39
    }
40
41
    /**
42
     * @inheritdoc
43
     */
44 13
    public function rules()
45
    {
46
        return [
47 13
            [['value'], 'string'],
48 13
            [['section', 'key'], 'string', 'max' => 255],
49
            [
50 13
                ['key'],
51 13
                'unique',
52 13
                'targetAttribute' => ['section', 'key'],
53 13
            ],
54 13
            ['type', 'in', 'range' => ['string', 'integer', 'boolean', 'float', 'double', 'object', 'null', 'ip', 'email', 'url']],
55 13
            [['created', 'modified'], 'safe'],
56 13
            [['active'], 'boolean'],
57 13
        ];
58
    }
59
60 29
    public function afterSave($insert, $changedAttributes)
61
    {
62 29
        parent::afterSave($insert, $changedAttributes);
63 29
        Yii::$app->settings->clearCache();
64 29
    }
65
66 4
    public function afterDelete()
67
    {
68 4
        parent::afterDelete();
69 4
        Yii::$app->settings->clearCache();
70 4
    }
71
72
    /**
73
     * @return array
74
     */
75 31
    public function behaviors()
76
    {
77
        return [
78
            'timestamp' => [
79 31
                'class' => TimestampBehavior::className(),
0 ignored issues
show
Deprecated Code introduced by
The method yii\base\BaseObject::className() has been deprecated with message: since 2.0.14. On PHP >=5.5, use `::class` instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
80
                'attributes' => [
81 31
                    ActiveRecord::EVENT_BEFORE_INSERT => 'created',
82 31
                    ActiveRecord::EVENT_BEFORE_UPDATE => 'modified',
83 31
                ],
84 31
                'value' => date('Y-m-d H:i:s'),//new Expression('NOW()'),
85 31
            ],
86 31
        ];
87
    }
88
89
    /**
90
     * @inheritdoc
91
     */
92 4
    public function getSettings()
93
    {
94 4
        $settings = static::find()->where(['active' => true])->asArray()->all();
95 4
        return array_merge_recursive(
96 4
            ArrayHelper::map($settings, 'key', 'value', 'section'),
97 4
            ArrayHelper::map($settings, 'key', 'type', 'section')
98 4
        );
99
    }
100
101
    /**
102
     * @inheritdoc
103
     */
104 9
    public function setSetting($section, $key, $value, $type = null)
105
    {
106 9
        $model = static::findOne(['section' => $section, 'key' => $key]);
107
108 9
        if ($model === null) {
109 8
            $model = new static();
110 8
            $model->active = 1;
111 8
        }
112 9
        $model->section = $section;
113 9
        $model->key = $key;
114 9
        $model->value = strval($value);
115
116 9
        if ($type !== null) {
117 1
            $model->type = $type;
118 9
        } elseif ( ! isset($model->type) ) {
119 7
            $type = $this->getValueType($value);
120 7
            $model->type = $type;
121 7
        }
122
123 9
        return $model->save();
124
    }
125
126
    /**
127
     * @inheritdoc
128
     */
129 6
    public function activateSetting($section, $key)
130
    {
131 6
        $model = static::findOne(['section' => $section, 'key' => $key]);
132
133 6
        if ($model && $model->active == 0) {
134 6
            $model->active = 1;
135 6
            return $model->save();
136
        }
137 1
        return false;
138
    }
139
140
    /**
141
     * @inheritdoc
142
     */
143 3
    public function deactivateSetting($section, $key)
144
    {
145 3
        $model = static::findOne(['section' => $section, 'key' => $key]);
146
147 3
        if ($model && $model->active == 1) {
148 3
            $model->active = 0;
149 3
            return $model->save();
150
        }
151 1
        return false;
152
    }
153
154
    /**
155
     * @inheritdoc
156
     */
157 2
    public function deleteSetting($section, $key)
158
    {
159 2
        $model = static::findOne(['section' => $section, 'key' => $key]);
160
161 2
        if ($model) {
162 2
            return $model->delete();
163
        }
164
        return true;
165
    }
166
167
    /**
168
     * @inheritdoc
169
     */
170 2
    public function deleteAllSettings()
171
    {
172 2
        return static::deleteAll();
0 ignored issues
show
Bug Best Practice introduced by
The return type of return static::deleteAll(); (integer) is incompatible with the return type declared by the interface pheme\settings\models\Se...face::deleteAllSettings of type boolean.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
173
    }
174
175
    /**
176
     * @inheritdoc
177
     */
178 1
    public function findSetting($key, $section = null)
179
    {
180 1
        if (is_null($section)) {
181
            $pieces = explode('.', $key, 2);
182
            if (count($pieces) > 1) {
183
                $section = $pieces[0];
184
                $key = $pieces[1];
185
            } else {
186
                $section = '';
187
            }
188
        }
189 1
        return $this->find()->where(['section' => $section, 'key' => $key])->limit(1)->one();
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->find()->wh...key))->limit(1)->one(); (yii\db\ActiveRecord|array|null) is incompatible with the return type declared by the interface pheme\settings\models\Se...gInterface::findSetting of type pheme\settings\models\SettingInterface.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
190
    }
191
192
    /**
193
     * @param $value
194
     * @return string|void
195
     */
196 7
    protected function getValueType($value)
197
    {
198
199 7
        if (filter_var($value, FILTER_VALIDATE_EMAIL)) {
200 1
            return 'email';
201
        }
202
203 6
        if (filter_var($value, FILTER_VALIDATE_URL)) {
204 1
            return 'url';
205
        }
206
207 5
        if (filter_var($value, FILTER_VALIDATE_IP)) {
208 1
            return 'ip';
209
        }
210
211 4
        if (filter_var($value, FILTER_VALIDATE_BOOLEAN)) {
212 1
            return 'boolean';
213
        }
214
215 3
        if (filter_var($value, FILTER_VALIDATE_INT)) {
216 1
            return 'integer';
217
        }
218
219 2
        if (filter_var($value, FILTER_VALIDATE_FLOAT)) {
220 1
            return 'float';
221
        }
222
223 1
        if (filter_var($value, FILTER_VALIDATE_FLOAT)) {
224
            return 'float';
225
        }
226
227 1
        $t = gettype($value);
228
229 1
        if ($t === 'string' && !empty($value)) {
230 1
            $error = false;
231
            try {
232 1
                Json::decode($value);
233 1
            } catch (InvalidArgumentException $e) {
234
                $error = true;
235
            }
236 1
            if (!$error) {
237 1
                $t = 'object';
238 1
            }
239 1
        }
240 1
        return $t;
241
    }
242
}
243