Passed
Push — master ( 4d325a...bebd8f )
by Alexey
02:23
created

FileStateForm::getPath()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 0
1
<?php
2
3
namespace dominus77\maintenance\models;
4
5
use Yii;
6
use yii\base\InvalidConfigException;
7
use yii\di\NotInstantiableException;
8
use yii\helpers\ArrayHelper;
9
use dominus77\maintenance\interfaces\StateFormInterface;
10
use dominus77\maintenance\BackendMaintenance;
11
use dominus77\maintenance\Maintenance;
12
use Exception;
13
use DateTime;
14
15
/**
16
 * Class FileStateForm
17
 * @package dominus77\maintenance\models
18
 *
19
 * @property string $dateTime
20
 * @property string $path
21
 * @property mixed $modeName
22
 * @property int $statusCode
23
 * @property int $timestamp
24
 */
25
class FileStateForm extends BaseForm implements StateFormInterface
26
{
27
    const MAINTENANCE_NOTIFY_SENDER_KEY = 'notifySender';
28
    const MAINTENANCE_UPDATE_KEY = 'maintenanceUpdate';
29
30
    /**
31
     * Select mode
32
     * @var string
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 = false;
55
    /**
56
     * CountDownWidget
57
     * @var bool
58
     */
59
    public $countDown = false;
60
61
    /**
62
     * Path to file
63
     * @var string
64
     */
65
    private $_path;
66
67
    /**
68
     * @throws InvalidConfigException
69
     * @throws NotInstantiableException
70
     */
71
    public function init()
72
    {
73
        parent::init();
74
        $this->_path = $this->state->getFileStatePath();
75
        $this->loadModel();
76
        if ($this->mode === null) {
77
            $this->mode = $this->state->isEnabled() ? Maintenance::STATUS_CODE_MAINTENANCE : Maintenance::STATUS_CODE_OK;
78
        }
79
    }
80
81
    /**
82
     * @inheritDoc
83
     * @return array
84
     */
85
    public function rules()
86
    {
87
        return [
88
            [['mode'], 'required'],
89
            [['mode'], 'number'],
90
            [['mode'], 'filter', 'filter' => [$this, 'integerTypeCast']],
91
92
            [['date'], 'string', 'min' => 19, 'max' => 19],
93
            ['date', 'default', 'value' => function () {
94
                return $this->getDateTime();
95
            }],
96
            [['date'], 'validateDateAttribute'],
97
98
            [['title', 'text'], 'string'],
99
100
            [['subscribe', 'countDown'], 'boolean', 'trueValue' => true, 'falseValue' => false, 'strict' => false]
101
        ];
102
    }
103
104
    /**
105
     * Type Cast integer
106
     *
107
     * @param $value string|integer
108
     * @return int
109
     */
110
    public function integerTypeCast($value)
111
    {
112
        return (int)$value;
113
    }
114
115
    /**
116
     * Validate date attribute
117
     *
118
     * @param $attribute
119
     * @throws InvalidConfigException
120
     */
121
    public function validateDateAttribute($attribute)
122
    {
123
        if ($attribute && !$this->validDate($this->$attribute)) {
124
            $example = $this->getDateTime();
125
            $this->addError($attribute, BackendMaintenance::t('app', 'Invalid date format. Use example: {:example}', [':example' => $example]));
126
        }
127
    }
128
129
    /**
130
     * Validate datetime
131
     *
132
     * @param $date
133
     * @return bool
134
     */
135
    public function validDate($date)
136
    {
137
        $d = DateTime::createFromFormat($this->getDateFormat(), $date);
138
        return $d && $d->format($this->getDateFormat()) === $date;
139
    }
140
141
    /**
142
     * @inheritDoc
143
     * @return array
144
     */
145
    public function attributeLabels()
146
    {
147
        return [
148
            'mode' => BackendMaintenance::t('app', 'Mode'),
149
            'date' => BackendMaintenance::t('app', 'Date and Time'),
150
            'title' => BackendMaintenance::t('app', 'Title'),
151
            'text' => BackendMaintenance::t('app', 'Text'),
152
            'subscribe' => BackendMaintenance::t('app', 'Subscribe'),
153
            'countDown' => BackendMaintenance::t('app', 'Count Down'),
154
        ];
155
    }
156
157
    /**
158
     * Path to file
159
     * @return string
160
     */
161
    public function getPath()
162
    {
163
        return $this->_path;
164
    }
165
166
    /**
167
     * Set data model
168
     */
169
    public function loadModel()
170
    {
171
        $stateArray = $this->prepareLoadModel($this->path);
172
        $this->load([$stateArray], false);
0 ignored issues
show
Bug introduced by
false of type false is incompatible with the type string expected by parameter $formName of yii\base\Model::load(). ( Ignorable by Annotation )

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

172
        $this->load([$stateArray], /** @scrutinizer ignore-type */ false);
Loading history...
173
    }
174
175
    /**
176
     * @return string
177
     */
178
    public function getTitle()
179
    {
180
        return BackendMaintenance::t('app', $this->state->defaultTitle);
0 ignored issues
show
Bug introduced by
Accessing defaultTitle on the interface dominus77\maintenance\interfaces\StateInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
181
    }
182
183
    /**
184
     * @return string
185
     */
186
    public function getText()
187
    {
188
        return BackendMaintenance::t('app', $this->state->defaultContent);
0 ignored issues
show
Bug introduced by
Accessing defaultContent on the interface dominus77\maintenance\interfaces\StateInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
189
    }
190
191
    /**
192
     * Current Datetime
193
     *
194
     * @return string
195
     * @throws InvalidConfigException
196
     */
197
    public function getDateTime()
198
    {
199
        return Yii::$app->formatter->asDatetime($this->getTimestamp(), 'php:' . $this->getDateFormat());
200
    }
201
202
    /**
203
     * Mode name
204
     *
205
     * @return mixed
206
     */
207
    public function getModeName()
208
    {
209
        return ArrayHelper::getValue(self::getModesArray(), $this->mode);
210
    }
211
212
    /**
213
     * Modes
214
     * @return array
215
     */
216
    public static function getModesArray()
217
    {
218
        return [
219
            Maintenance::STATUS_CODE_OK => BackendMaintenance::t('app', 'Mode normal'),
220
            Maintenance::STATUS_CODE_MAINTENANCE => BackendMaintenance::t('app', 'Mode maintenance'),
221
        ];
222
    }
223
224
    /**
225
     * Save this in file
226
     *
227
     * @return bool|int
228
     */
229
    public function save()
230
    {
231
        $result = false;
232
        if ($this->mode === Maintenance::STATUS_CODE_MAINTENANCE) {
0 ignored issues
show
introduced by
The condition $this->mode === dominus7...STATUS_CODE_MAINTENANCE is always false.
Loading history...
233
            file_put_contents($this->path,
234
                $this->prepareData());
235
            chmod($this->path, 0765);
236
            $result = true;
237
        }
238
        if ($this->mode === Maintenance::STATUS_CODE_OK) {
0 ignored issues
show
introduced by
The condition $this->mode === dominus7...tenance::STATUS_CODE_OK is always false.
Loading history...
239
            $model = new SubscribeForm();
240
            $result = $model->send();
241
            $this->disable();
242
        }
243
        return $result;
244
    }
245
246
    /**
247
     * @return string
248
     */
249
    public function prepareData()
250
    {
251
        $result = '';
252
        foreach ($this->attributes as $attribute => $value) {
253
            $value = trim($value);
254
            if ($value) {
255
                $result .= $attribute . ' = ' . $value . PHP_EOL;
256
            }
257
        }
258
        return $result;
259
    }
260
261
    /**
262
     * Enable
263
     *
264
     * @return bool|mixed
265
     */
266
    public function enable()
267
    {
268
        return $this->state->enable();
269
    }
270
271
    /**
272
     * Disable
273
     *
274
     * @return bool|mixed
275
     */
276
    public function disable()
277
    {
278
        return $this->state->disable();
279
    }
280
281
    /**
282
     * @return int
283
     * @throws Exception
284
     */
285
    public function getTimestamp()
286
    {
287
        $date = new DateTime(date($this->getDateFormat()));
288
        if ($this->validDate($this->date)) {
289
            $date = new DateTime($this->date);
290
        }
291
        return $date->getTimestamp();
292
    }
293
294
    /**
295
     * @return bool
296
     */
297
    public function isTimer()
298
    {
299
        return (bool)$this->countDown;
300
    }
301
302
    /**
303
     * @return bool
304
     */
305
    public function isSubscribe()
306
    {
307
        return (bool)$this->subscribe;
308
    }
309
310
    /**
311
     * Return true is enable maintenance mode
312
     *
313
     * @return bool
314
     */
315
    public function isEnabled()
316
    {
317
        return $this->state->isEnabled() && ($this->mode !== Maintenance::STATUS_CODE_OK);
318
    }
319
320
    /**
321
     * StatusCode
322
     *
323
     * @return string
324
     */
325
    public function getStatusCode()
326
    {
327
        return $this->mode;
328
    }
329
}
330