Completed
Push — master ( fab37c...20384e )
by Alex
02:09
created

BaseSetting::getValueType()   B

Complexity

Conditions 11
Paths 11

Size

Total Lines 42

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 22
CRAP Score 11

Importance

Changes 0
Metric Value
dl 0
loc 42
ccs 22
cts 22
cp 1
rs 7.3166
c 0
b 0
f 0
cc 11
nc 11
nop 1
crap 11

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 36
    public static function tableName()
37
    {
38 36
        return '{{%settings}}';
39
    }
40
41
    /**
42
     * @inheritdoc
43
     */
44 18
    public function rules()
45
    {
46
        return [
47 18
            [['value'], 'string'],
48
            [['section', 'key'], 'string', 'max' => 255],
49
            [
50
                ['key'],
51
                'unique',
52
                'targetAttribute' => ['section', 'key'],
53
            ],
54
            ['type', 'in', 'range' => ['string', 'integer', 'boolean', 'float', 'double', 'object', 'null', 'ip', 'email', 'url']],
55
            [['created', 'modified'], 'safe'],
56
            [['active'], 'boolean'],
57
        ];
58
    }
59
60 34
    public function afterSave($insert, $changedAttributes)
61
    {
62 34
        parent::afterSave($insert, $changedAttributes);
63 34
        Yii::$app->settings->clearCache();
64 34
    }
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 36
    public function behaviors()
76
    {
77
        return [
78
            'timestamp' => [
79 36
                '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 36
                    ActiveRecord::EVENT_BEFORE_INSERT => 'created',
82 36
                    ActiveRecord::EVENT_BEFORE_UPDATE => 'modified',
83
                ],
84 36
                'value' => date('Y-m-d H:i:s'),//new Expression('NOW()'),
85
            ],
86
        ];
87
    }
88
89
    /**
90
     * @inheritdoc
91
     */
92 7
    public function getSettings()
93
    {
94 7
        $settings = static::find()->where(['active' => true])->asArray()->all();
95 7
        return array_merge_recursive(
96 7
            ArrayHelper::map($settings, 'key', 'value', 'section'),
97 7
            ArrayHelper::map($settings, 'key', 'type', 'section')
98
        );
99
    }
100
101
    /**
102
     * @inheritdoc
103
     */
104 14
    public function setSetting($section, $key, $value, $type = null)
105
    {
106 14
        $model = static::findOne(['section' => $section, 'key' => $key]);
107
108 14
        if ($model === null) {
109 13
            $model = new static();
110 13
            $model->active = 1;
111
        }
112 14
        $model->section = $section;
113 14
        $model->key = $key;
114 14
        $model->value = strval($value);
115
116 14
        if ($type !== null) {
117 2
            $model->type = $type;
118 12
        } elseif ( ! isset($model->type) ) {
119 11
            $type = $this->getValueType($value);
120 11
            $model->type = $type;
121
        }
122
123 14
        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 4
    public function deactivateSetting($section, $key)
144
    {
145 4
        $model = static::findOne(['section' => $section, 'key' => $key]);
146
147 4
        if ($model && $model->active == 1) {
148 4
            $model->active = 0;
149 4
            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
    }
165
166
    /**
167
     * @inheritdoc
168
     */
169 2
    public function deleteAllSettings()
170
    {
171 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...
172
    }
173
174
    /**
175
     * @inheritdoc
176
     */
177 2
    public function findSetting($key, $section = null)
178
    {
179 2
        if (is_null($section)) {
180 2
            $pieces = explode('.', $key, 2);
181 2
            if (count($pieces) > 1) {
182 2
                $section = $pieces[0];
183 2
                $key = $pieces[1];
184
            } else {
185
                $section = '';
186
            }
187
        }
188 2
        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...
189
    }
190
191
    /**
192
     * @param $value
193
     * @return string|void
194
     */
195 11
    protected function getValueType($value)
196
    {
197
198 11
        if (filter_var($value, FILTER_VALIDATE_EMAIL)) {
199 1
            return 'email';
200
        }
201
202 10
        if (filter_var($value, FILTER_VALIDATE_URL)) {
203 1
            return 'url';
204
        }
205
206 9
        if (filter_var($value, FILTER_VALIDATE_IP)) {
207 1
            return 'ip';
208
        }
209
210 8
        if (filter_var($value, FILTER_VALIDATE_BOOLEAN)) {
211 1
            return 'boolean';
212
        }
213
214 7
        if (filter_var($value, FILTER_VALIDATE_INT)) {
215 2
            return 'integer';
216
        }
217
218 5
        if (filter_var($value, FILTER_VALIDATE_FLOAT)) {
219 1
            return 'float';
220
        }
221
222 4
        $t = gettype($value);
223
224 4
        if ($t === 'string' && !empty($value)) {
225 4
            $error = false;
226
            try {
227 4
                Json::decode($value);
228 2
            } catch (InvalidArgumentException $e) {
229 2
                $error = true;
230
            }
231 4
            if (!$error) {
232 2
                $t = 'object';
233
            }
234
        }
235 4
        return $t;
236
    }
237
}
238