ContactForm::contact()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 15
rs 9.7666
c 0
b 0
f 0
cc 2
nc 2
nop 1
1
<?php
2
3
namespace app\models\forms;
4
5
use Yii;
6
use yii\base\Model;
7
8
/**
9
 * ContactForm is the model behind the contact form.
10
 */
11
class ContactForm extends Model
12
{
13
    /**
14
     * @var string username
15
     */
16
    public $name;
17
18
    /**
19
     * @var string email
20
     */
21
    public $email;
22
23
    /**
24
     * @var string subject
25
     */
26
    public $subject;
27
28
    /**
29
     * @var string body
30
     */
31
    public $body;
32
33
    /**
34
     * @var string verifyCode
35
     */
36
    public $verifyCode;
37
38
    /**
39
     * @return array the validation rules
40
     */
41
    public function rules(): array
42
    {
43
        return [
44
            [['name', 'email', 'subject', 'body'], 'required'],
45
            ['email', 'email'],
46
            ['verifyCode', 'captcha'],
47
        ];
48
    }
49
50
    /**
51
     * @return array customized attribute labels
52
     */
53
    public function attributeLabels(): array
54
    {
55
        return [
56
            'name' => Yii::t('contact', 'Name'),
57
            'email' => Yii::t('contact', 'Email'),
58
            'subject' => Yii::t('contact', 'Subject'),
59
            'body' => Yii::t('contact', 'Body'),
60
            'verifyCode' => Yii::t('contact', 'Verification Code'),
61
        ];
62
    }
63
64
    /**
65
     * Sends an email to the specified email address using the information collected by this model.
66
     *
67
     * @param string $email the target email address
68
     *
69
     * @return bool whether the model passes validation
70
     */
71
    public function contact(string $email): bool
72
    {
73
        if ($this->validate()) {
74
            Yii::$app->mailer->compose()
75
                ->setTo($email)
76
                ->setFrom([$this->email => $this->name])
77
                ->setSubject($this->subject)
78
                ->setTextBody($this->body)
79
                ->send();
80
81
            return true;
82
        }
83
84
        return false;
85
    }
86
}
87