Passed
Push — master ( 609fbb...fb764c )
by Alexey
02:15
created

SubscribeForm::getFilePath()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
eloc 1
c 1
b 1
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 1
1
<?php
2
3
namespace dominus77\maintenance\models;
4
5
use Yii;
6
use yii\helpers\ArrayHelper;
7
use dominus77\maintenance\interfaces\SubscribeFormInterface;
8
use dominus77\maintenance\BackendMaintenance;
9
use RuntimeException;
10
11
/**
12
 * Class SubscribeForm
13
 * @package dominus77\maintenance\models
14
 *
15
 * @property array $emails
16
 */
17
class SubscribeForm extends BaseForm implements SubscribeFormInterface
18
{
19
    const SUBSCRIBE_SUCCESS = 'subscribeSuccess';
20
    const SUBSCRIBE_INFO = 'subscribeInfo';
21
22
    /**
23
     * @var string
24
     */
25
    public $email;
26
27
    /**
28
     * @var array
29
     */
30
    protected $followers;
31
32
    /**
33
     * @var array
34
     */
35
    protected $subscribeOptions;
36
37
    /**
38
     * @inheritDoc
39
     */
40
    public function init()
41
    {
42
        parent::init();
43
        $urlManager = Yii::$app->urlManager;
44
        $subscribeOptions = [
45
            'template' => $this->state->getSubscribeOptionsTemplate(),
0 ignored issues
show
Bug introduced by
The method getSubscribeOptionsTemplate() does not exist on dominus77\maintenance\interfaces\StateInterface. Since it exists in all sub-types, consider adding an abstract or default implementation to dominus77\maintenance\interfaces\StateInterface. ( Ignorable by Annotation )

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

45
            'template' => $this->state->/** @scrutinizer ignore-call */ getSubscribeOptionsTemplate(),
Loading history...
46
            'backLink' => $urlManager->hostInfo, // Link in a letter to the site
47
            'from' => $this->getFrom('[email protected]'),
48
            'subject' => BackendMaintenance::t('app', 'Notification of completion of technical work')
49
        ];
50
        $this->subscribeOptions = ArrayHelper::merge($subscribeOptions, $this->state->subscribeOptions);
0 ignored issues
show
Bug introduced by
Accessing subscribeOptions on the interface dominus77\maintenance\interfaces\StateInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
51
        $this->setFollowers();
52
    }
53
54
    /**
55
     * @inheritDoc
56
     * @return array
57
     */
58
    public function rules()
59
    {
60
        return [
61
            ['email', 'trim'],
62
            ['email', 'required'],
63
            ['email', 'email'],
64
            ['email', 'string', 'max' => 255],
65
        ];
66
    }
67
68
    /**
69
     * @inheritDoc
70
     * @return array
71
     */
72
    public function attributeLabels()
73
    {
74
        return [
75
            'email' => BackendMaintenance::t('app', 'Your email'),
76
        ];
77
    }
78
79
    /**
80
     * Sending notifications to followers
81
     *
82
     * @return int
83
     */
84
    public function send()
85
    {
86
        try {
87
            $emails = $this->getEmails();
88
            $messages = [];
89
            $mailer = Yii::$app->mailer;
90
            foreach ($emails as $email) {
91
                $messages[] = $mailer->compose(
92
                    $this->subscribeOptions['template'], [
93
                    'backLink' => $this->subscribeOptions['backLink']
94
                ])
95
                    ->setFrom([$this->subscribeOptions['from'] => Yii::$app->name])
96
                    ->setTo($email)
97
                    ->setSubject($this->subscribeOptions['subject']);
98
99
            }
100
            $result = $mailer->sendMultiple($messages);
101
            if ($result >= 0) {
102
                $this->deleteFile();
103
            }
104
            return $result;
105
        } catch (RuntimeException $e) {
106
            throw new RuntimeException(
107
                'Attention: Error sending notifications to subscribers!'
108
            );
109
        }
110
    }
111
112
    /**
113
     * Save email in file
114
     *
115
     * @return bool
116
     */
117
    public function save()
118
    {
119
        $str = $this->prepareData();
120
        $file = $this->state->getSubscribePath();
0 ignored issues
show
Bug introduced by
The method getSubscribePath() does not exist on dominus77\maintenance\interfaces\StateInterface. Since it exists in all sub-types, consider adding an abstract or default implementation to dominus77\maintenance\interfaces\StateInterface. ( Ignorable by Annotation )

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

120
        /** @scrutinizer ignore-call */ 
121
        $file = $this->state->getSubscribePath();
Loading history...
121
        try {
122
            if (is_string($file) && $str && $fp = fopen($file, 'ab')) {
123
                fwrite($fp, $str . PHP_EOL);
124
                fclose($fp);
125
                return chmod($file, 0765);
126
            }
127
            return false;
128
        } catch (RuntimeException $e) {
129
            throw new RuntimeException(
130
                "Attention: Subscriber cannot be added because {$file} could not be save."
131
            );
132
        }
133
    }
134
135
    /**
136
     * Delete subscribers file
137
     * @return bool
138
     */
139
    public function deleteFile()
140
    {
141
        $file = $this->state->getSubscribePath();
142
        try {
143
            $result = false;
144
            if (file_exists($file)) {
145
                $result = unlink($file);
146
            }
147
            return $result;
148
        } catch (RuntimeException $e) {
149
            throw new RuntimeException(
150
                "Attention: Error deleting {$file} file."
151
            );
152
        }
153
    }
154
155
    /**
156
     * This prepare data on before save
157
     * @return string
158
     */
159
    protected function prepareData()
160
    {
161
        return date($this->dateFormat) . ' = ' . $this->email;
162
    }
163
164
    /**
165
     * Save follower
166
     * @return bool
167
     */
168
    public function subscribe()
169
    {
170
        if ($this->isEmail()) {
171
            return false;
172
        }
173
        return $this->save();
174
    }
175
176
    /**
177
     * Emails subscribe
178
     * @return array
179
     */
180
    public function getEmails()
181
    {
182
        $subscribeData = $this->prepareLoadModel($this->state->getSubscribePath());
183
        $emails = [];
184
        foreach ($subscribeData as $email) {
185
            $emails[] = $email;
186
        }
187
        return $emails;
188
    }
189
190
    /**
191
     * Check email is subscribe
192
     * @return bool
193
     */
194
    public function isEmail()
195
    {
196
        return ArrayHelper::isIn($this->email, $this->getEmails());
197
    }
198
199
    /**
200
     * @return array
201
     */
202
    public function getFollowers()
203
    {
204
        $items = [];
205
        foreach ($this->followers as $follower) {
206
            $items[]['email'] = $follower;
207
        }
208
        return $items;
209
    }
210
211
    /**
212
     * @param array $followers
213
     */
214
    public function setFollowers($followers = [])
215
    {
216
        $this->followers = $followers ?: $this->getEmails();
217
    }
218
219
    /**
220
     * From
221
     * @param $from string
222
     * @return mixed|string
223
     */
224
    protected function getFrom($from)
225
    {
226
        if (isset(Yii::$app->params['senderEmail']) && !empty(Yii::$app->params['senderEmail'])) {
227
            $from = Yii::$app->params['senderEmail'];
228
        } else if (isset(Yii::$app->params['supportEmail']) && !empty(Yii::$app->params['supportEmail'])) {
229
            $from = Yii::$app->params['supportEmail'];
230
        }
231
        return $from;
232
    }
233
}
234