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