Completed
Push — master ( b812ef...80282b )
by monster
01:45
created

BaseSetting::getSettings()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 8
ccs 6
cts 6
cp 1
rs 9.4285
cc 1
eloc 5
nc 1
nop 0
crap 1
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\helpers\Json;
12
use yii\db\Expression;
13
use yii\db\ActiveRecord;
14
use yii\helpers\ArrayHelper;
15
use yii\base\InvalidParamException;
16
use yii\behaviors\TimestampBehavior;
17
18
/**
19
 * This is the model class for table "settings".
20
 *
21
 * @property integer $id
22
 * @property string $type
23
 * @property string $section
24
 * @property string $key
25
 * @property string $value
26
 * @property boolean $active
27
 * @property string $created
28
 * @property string $modified
29
 *
30
 * @author Aris Karageorgos <[email protected]>
31
 */
32
class BaseSetting extends ActiveRecord implements SettingInterface
33
{
34
    /**
35
     * @inheritdoc
36
     */
37 18
    public static function tableName()
38
    {
39 18
        return '{{%settings}}';
40
    }
41
42
    /**
43
     * @inheritdoc
44
     */
45 4
    public function rules()
46
    {
47
        return [
48 4
            [['value'], 'string'],
49 4
            [['section', 'key'], 'string', 'max' => 255],
50
            [
51 4
                ['key'],
52 4
                'unique',
53 4
                'targetAttribute' => ['section', 'key'],
54 4
            ],
55 4
            ['type', 'in', 'range' => ['string', 'integer', 'boolean', 'float', 'double', 'object', 'null']],
56 4
            [['created', 'modified'], 'safe'],
57 4
            [['active'], 'boolean'],
58 4
        ];
59
    }
60
61 17
    public function afterSave($insert, $changedAttributes)
62
    {
63 17
        parent::afterSave($insert, $changedAttributes);
64 17
        Yii::$app->settings->clearCache();
65 17
    }
66
67 4
    public function afterDelete()
68
    {
69 4
        parent::afterDelete();
70 4
        Yii::$app->settings->clearCache();
71 4
    }
72
73
    /**
74
     * @return array
75
     */
76 18
    public function behaviors()
77
    {
78
        return [
79
            'timestamp' => [
80 18
                'class' => TimestampBehavior::className(),
81
                'attributes' => [
82 18
                    ActiveRecord::EVENT_BEFORE_INSERT => 'created',
83 18
                    ActiveRecord::EVENT_BEFORE_UPDATE => 'modified',
84 18
                ],
85 18
                'value' => new Expression('NOW()'),
86 18
            ],
87 18
        ];
88
    }
89
90
    /**
91
     * @inheritdoc
92
     */
93 2
    public function getSettings()
94
    {
95 2
        $settings = static::find()->where(['active' => true])->asArray()->all();
96 2
        return array_merge_recursive(
97 2
            ArrayHelper::map($settings, 'key', 'value', 'section'),
98 2
            ArrayHelper::map($settings, 'key', 'type', 'section')
99 2
        );
100
    }
101
102
    /**
103
     * @inheritdoc
104
     */
105 2
    public function setSetting($section, $key, $value, $type = null)
106
    {
107 2
        $model = static::findOne(['section' => $section, 'key' => $key]);
108
109 2
        if ($model === null) {
110
            $model = new static();
111
            $model->active = 1;
112
        }
113 2
        $model->section = $section;
114 2
        $model->key = $key;
115 2
        $model->value = strval($value);
116
117 2
        if ($type !== null) {
118 1
            $model->type = $type;
119 1
        } else {
120 1
            $t = gettype($value);
121 1
            if ($t == 'string') {
122 1
                $error = false;
123
                try {
124 1
                    Json::decode($value);
125 1
                } catch (InvalidParamException $e) {
126 1
                    $error = true;
127
                }
128 1
                if (!$error) {
129
                    $t = 'object';
130
                }
131 1
            }
132 1
            $model->type = $t;
133
        }
134
135 2
        return $model->save();
136
    }
137
138
    /**
139
     * @inheritdoc
140
     */
141 4
    public function activateSetting($section, $key)
142
    {
143 4
        $model = static::findOne(['section' => $section, 'key' => $key]);
144
145 4
        if ($model && $model->active == 0) {
146 4
            $model->active = 1;
147 4
            return $model->save();
148
        }
149
        return false;
150
    }
151
152
    /**
153
     * @inheritdoc
154
     */
155 2
    public function deactivateSetting($section, $key)
156
    {
157 2
        $model = static::findOne(['section' => $section, 'key' => $key]);
158
159 2
        if ($model && $model->active == 1) {
160 2
            $model->active = 0;
161 2
            return $model->save();
162
        }
163
        return false;
164
    }
165
166
    /**
167
     * @inheritdoc
168
     */
169 2
    public function deleteSetting($section, $key)
170
    {
171 2
        $model = static::findOne(['section' => $section, 'key' => $key]);
172
173 2
        if ($model) {
174 2
            return $model->delete();
0 ignored issues
show
Bug Compatibility introduced by
The expression $model->delete(); of type false|integer adds the type integer to the return on line 174 which is incompatible with the return type declared by the interface pheme\settings\models\Se...nterface::deleteSetting of type boolean.
Loading history...
175
        }
176
        return true;
177
    }
178
179
    /**
180
     * @inheritdoc
181
     */
182 2
    public function deleteAllSettings()
183
    {
184 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...
185
    }
186
187
    /**
188
     * @inheritdoc
189
     */
190 2
    public function findSetting($key, $section = null)
191
    {
192 2
        if (is_null($section)) {
193
            $pieces = explode('.', $key, 2);
194
            if (count($pieces) > 1) {
195
                $section = $pieces[0];
196
                $key = $pieces[1];
197
            } else {
198
                $section = '';
199
            }
200
        }
201 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...
202
    }
203
}
204