Completed
Push — master ( ff2b0b...f369f8 )
by Alexey
05:58
created

FileStateForm::isEnabled()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 0
1
<?php
2
3
namespace common\components\maintenance\models;
4
5
use Yii;
6
use yii\base\Model;
7
use yii\base\InvalidConfigException;
8
use yii\helpers\ArrayHelper;
9
use common\components\maintenance\interfaces\StateInterface;
10
use common\components\maintenance\states\FileState;
11
use Exception;
12
13
/**
14
 * Class FileStateForm
15
 * @package common\components\maintenance\models
16
 *
17
 * @property mixed $followers
18
 * @property mixed $datetime
19
 * @property mixed $modeName
20
 * @property string $dateFormat
21
 * @property int $timestamp
22
 */
23
class FileStateForm extends Model
24
{
25
    const MODE_MAINTENANCE_ON = 'On';
26
    const MODE_MAINTENANCE_OFF = 'Off';
27
    const MAINTENANCE_NOTIFY_SENDER_KEY = 'notifySender';
28
    const MAINTENANCE_UPDATE_KEY = 'maintenanceUpdate';
29
30
    /**
31
     * Select mode
32
     * @var array
33
     */
34
    public $mode;
35
    /**
36
     * Datetime
37
     * @var string
38
     */
39
    public $date;
40
    /**
41
     * Title
42
     * @var string
43
     */
44
    public $title;
45
    /**
46
     * Text
47
     * @var string
48
     */
49
    public $text;
50
    /**
51
     * Subscribe
52
     * @var bool
53
     */
54
    public $subscribe = true;
55
    /**
56
     * CountDown
57
     * @var bool
58
     */
59
    public $countDown = true;
60
61
    /**
62
     * @var StateInterface
63
     */
64
    protected $state;
65
66
    /**
67
     * @var array
68
     */
69
    private $followers;
70
71
    /**
72
     * @inheritDoc
73
     */
74
    public function init()
75
    {
76
        parent::init();
77
        $this->state = Yii::$container->get(StateInterface::class);
78
        $this->mode = self::MODE_MAINTENANCE_OFF;
0 ignored issues
show
Documentation Bug introduced by
It seems like self::MODE_MAINTENANCE_OFF of type string is incompatible with the declared type array of property $mode.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
79
        $this->date = $this->datetime;
80
        $this->title = $this->title ?: Yii::t('app', $this->state->defaultTitle);
81
        $this->text = $this->text ?: Yii::t('app', $this->state->defaultContent);
82
        $this->setFollowers();
83
        $this->setData();
84
    }
85
86
    /**
87
     * @inheritDoc
88
     * @return array
89
     */
90
    public function rules()
91
    {
92
        return [
93
            ['date', 'trim'],
94
            ['mode', 'required'],
95
            ['date', 'string', 'max' => 19],
96
            ['date', 'validateDateAttribute'],
97
            [['title', 'text'], 'string'],
98
            [['subscribe', 'countDown'], 'boolean']
99
        ];
100
    }
101
102
    /**
103
     * @param $attribute
104
     * @throws InvalidConfigException
105
     */
106
    public function validateDateAttribute($attribute)
107
    {
108
        if ($attribute && !$this->state->validDate($this->$attribute)) {
0 ignored issues
show
Bug introduced by
The method validDate() does not exist on common\components\mainte...terfaces\StateInterface. Since it exists in all sub-types, consider adding an abstract or default implementation to common\components\mainte...terfaces\StateInterface. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

108
        if ($attribute && !$this->state->/** @scrutinizer ignore-call */ validDate($this->$attribute)) {
Loading history...
109
            $example = Yii::$app->formatter->asDatetime(time(), 'php:' . $this->state->dateFormat);
0 ignored issues
show
Bug introduced by
Accessing dateFormat on the interface common\components\mainte...terfaces\StateInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
110
            $this->addError($attribute, Yii::t('app', 'Invalid date format. Use example: {:example}', [':example' => $example]));
111
        }
112
    }
113
114
    /**
115
     * @inheritDoc
116
     * @return array
117
     */
118
    public function attributeLabels()
119
    {
120
        return [
121
            'mode' => Yii::t('app', 'Mode'),
122
            'date' => Yii::t('app', 'Date and Time'),
123
            'title' => Yii::t('app', 'Title'),
124
            'text' => Yii::t('app', 'Text'),
125
            'subscribe' => Yii::t('app', 'Subscribe'),
126
            'countDown' => Yii::t('app', 'Count Down'),
127
        ];
128
    }
129
130
    /**
131
     * Mode name
132
     * @return mixed
133
     */
134
    public function getModeName()
135
    {
136
        return ArrayHelper::getValue(self::getModesArray(), $this->mode);
137
    }
138
139
    /**
140
     * Modes
141
     * @return array
142
     */
143
    public static function getModesArray()
144
    {
145
        return [
146
            self::MODE_MAINTENANCE_OFF => Yii::t('app', 'Mode normal'),
147
            self::MODE_MAINTENANCE_ON => Yii::t('app', 'Mode maintenance'),
148
        ];
149
    }
150
151
    /**
152
     * Save this in file
153
     */
154
    public function save()
155
    {
156
        $result = false;
157
        if ($this->mode === self::MODE_MAINTENANCE_ON) {
0 ignored issues
show
introduced by
The condition $this->mode === self::MODE_MAINTENANCE_ON is always false.
Loading history...
158
            if ($this->isEnabled()) {
159
                $this->update();
160
                Yii::$app->session->setFlash(self::MAINTENANCE_UPDATE_KEY, Yii::t('app', 'Maintenance mode successfully updated!'));
161
                $result = true;
162
            } else {
163
                $this->enable();
164
                $result = true;
165
            }
166
        }
167
        if ($this->mode === self::MODE_MAINTENANCE_OFF) {
0 ignored issues
show
introduced by
The condition $this->mode === self::MODE_MAINTENANCE_OFF is always false.
Loading history...
168
            $count = $this->disable();
169
            Yii::$app->session->setFlash(self::MAINTENANCE_NOTIFY_SENDER_KEY, Yii::t('app',
170
                '{n, plural, =0{no followers} =1{one message sent} other{# messages sent}}',
171
                ['n' => $count])
172
            );
173
            $result = true;
174
        }
175
        return $result;
176
    }
177
178
    /**
179
     * Enable
180
     * @return mixed
181
     */
182
    public function enable()
183
    {
184
        $subscribe = $this->subscribe ? FileState::MAINTENANCE_SUBSCRIBE_ON : FileState::MAINTENANCE_SUBSCRIBE_OFF;
185
        return $this->state->enable($this->date, $this->title, $this->text, $subscribe);
186
    }
187
188
    /**
189
     * Update
190
     * @return array
191
     */
192
    public function update()
193
    {
194
        $result = [];
195
        foreach ($this->attributes as $key => $value) {
196
            if ($key === FileState::MAINTENANCE_PARAM_SUBSCRIBE) {
197
                $value = $value ? FileState::MAINTENANCE_SUBSCRIBE_ON : FileState::MAINTENANCE_SUBSCRIBE_OFF;
198
            }
199
            $result[$key] = $this->state->update($key, $value);
200
        }
201
        return $result;
202
    }
203
204
    /**
205
     * Disable
206
     * @return int|mixed
207
     */
208
    public function disable()
209
    {
210
        return $this->state->disable();
211
    }
212
213
    /**
214
     * @return mixed
215
     * @throws Exception
216
     */
217
    public function getDatetime()
218
    {
219
        return $this->state->datetime($this->getTimestamp(), $this->state->dateFormat);
0 ignored issues
show
Bug introduced by
The method datetime() does not exist on common\components\mainte...terfaces\StateInterface. Since it exists in all sub-types, consider adding an abstract or default implementation to common\components\mainte...terfaces\StateInterface. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

219
        return $this->state->/** @scrutinizer ignore-call */ datetime($this->getTimestamp(), $this->state->dateFormat);
Loading history...
Bug introduced by
Accessing dateFormat on the interface common\components\mainte...terfaces\StateInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
220
    }
221
222
    /**
223
     * @return int
224
     * @throws Exception
225
     */
226
    public function getTimestamp()
227
    {
228
        return $this->state->timestamp();
0 ignored issues
show
Bug introduced by
The method timestamp() does not exist on common\components\mainte...terfaces\StateInterface. Since it exists in all sub-types, consider adding an abstract or default implementation to common\components\mainte...terfaces\StateInterface. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

228
        return $this->state->/** @scrutinizer ignore-call */ timestamp();
Loading history...
229
    }
230
231
    /**
232
     * @return array
233
     */
234
    public function getFollowers()
235
    {
236
        $items = [];
237
        foreach ($this->followers as $follower) {
238
            $items[]['email'] = $follower;
239
        }
240
        return $items;
241
    }
242
243
    /**
244
     * @param array $followers
245
     */
246
    public function setFollowers($followers = [])
247
    {
248
        $this->followers = $followers ?: $this->state->emails();
0 ignored issues
show
Bug introduced by
The method emails() does not exist on common\components\mainte...terfaces\StateInterface. Since it exists in all sub-types, consider adding an abstract or default implementation to common\components\mainte...terfaces\StateInterface. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

248
        $this->followers = $followers ?: $this->state->/** @scrutinizer ignore-call */ emails();
Loading history...
249
    }
250
251
    /**
252
     * @return bool
253
     */
254
    public function isEnabled()
255
    {
256
        return $this->state->isEnabled();
257
    }
258
259
    /**
260
     * @return string
261
     */
262
    public function getDateFormat()
263
    {
264
        return $this->state->dateFormat;
0 ignored issues
show
Bug introduced by
Accessing dateFormat on the interface common\components\mainte...terfaces\StateInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
265
    }
266
267
    /**
268
     * Set data is enabled
269
     */
270
    private function setData()
271
    {
272
        if ($this->isEnabled()) {
273
            $this->mode = self::MODE_MAINTENANCE_ON;
0 ignored issues
show
Documentation Bug introduced by
It seems like self::MODE_MAINTENANCE_ON of type string is incompatible with the declared type array of property $mode.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
274
            $this->date = $this->datetime;
275
            $this->title = $this->state->getParams(FileState::MAINTENANCE_PARAM_TITLE);
0 ignored issues
show
Bug introduced by
The method getParams() does not exist on common\components\mainte...terfaces\StateInterface. Since it exists in all sub-types, consider adding an abstract or default implementation to common\components\mainte...terfaces\StateInterface. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

275
            /** @scrutinizer ignore-call */ 
276
            $this->title = $this->state->getParams(FileState::MAINTENANCE_PARAM_TITLE);
Loading history...
276
            $this->text = $this->state->getParams(FileState::MAINTENANCE_PARAM_CONTENT);
277
            $subscribe = $this->state->getParams(FileState::MAINTENANCE_PARAM_SUBSCRIBE);
278
            $this->subscribe = ($subscribe === FileState::MAINTENANCE_SUBSCRIBE_ON);
279
            $this->countDown = true;
280
        }
281
    }
282
}
283