Completed
Push — master ( 89be15...80fd60 )
by Igor
11:15
created

ConfirmEmail::sendEmail()   B

Complexity

Conditions 3
Paths 4

Size

Total Lines 24
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 24
rs 8.9713
c 0
b 0
f 0
cc 3
eloc 15
nc 4
nop 1
1
<?php
2
3
namespace app\modules\auth\services;
4
5
use Yii;
6
use yii\base\{Exception, UserException};
7
use yii\web\BadRequestHttpException;
8
use app\models\entity\User;
9
10
class ConfirmEmail
11
{
12
    /**
13
     * Confirm email
14
     *
15
     * @param string $token
16
     * @throws BadRequestHttpException
17
     */
18
    public function setConfirmed(string $token): void
19
    {
20
        $tokenizer = new Tokenizer();
21
22
        if ($tokenizer->validate($token)) {
23
            $user = User::find()->emailConfirmToken($token)->one();
24
25
            if ($user) {
26
                $user->setConfirmed();
27
                if (!$user->save()) {
28
                    throw new Exception(Yii::t('app.msg', 'An error occurred while confirming'));
29
                }
30
                return;
31
            }
32
        }
33
34
        throw new BadRequestHttpException(Yii::t('app.msg', 'Invalid token for activate account'));
35
    }
36
37
    /**
38
     * Sends an email with a link, for confirm the email
39
     *
40
     * @throws UserException
41
     */
42
    public function sendEmail(User $user): void
43
    {
44
        $tokenizer = new Tokenizer();
45
        if (!$tokenizer->validate($user->email_confirm_token)) {
46
            $user->setEmailConfirmToken($tokenizer->generate());
47
            $user->updateAttributes([
48
                'email_confirm_token' => $user->email_confirm_token,
49
                'date_confirm' => $user->date_confirm,
50
            ]);
51
        }
52
53
        $sent = Yii::$app->notify->sendMessage(
54
            $user->email,
55
            Yii::t('app', 'Activate Your Account'),
56
            'emailConfirmToken',
57
            ['user' => $user]
58
        );
59
60
        if (!$sent) {
61
            throw new UserException(
62
                Yii::t('app.msg', 'An error occurred while sending a message to activate account')
63
            );
64
        }
65
    }
66
}
67