Completed
Push — master ( c3cfbd...a5cba6 )
by Igor
01:40
created

ConfirmEmail   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 61
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 7

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 7
dl 0
loc 61
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A setConfirmed() 0 16 4
A sendEmail() 0 23 3
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
    private $tokenizer;
13
14
    public function __construct(Tokenizer $tokenizer)
15
    {
16
        $this->tokenizer = $tokenizer;
17
    }
18
19
    /**
20
     * Confirm email
21
     *
22
     * @param string $token
23
     * @throws BadRequestHttpException
24
     */
25
    public function setConfirmed(string $token): void
26
    {
27
        if ($this->tokenizer->validate($token)) {
28
            $user = User::find()->emailConfirmToken($token)->one();
29
30
            if ($user) {
31
                $user->setConfirmed();
32
                if (!$user->save()) {
33
                    throw new Exception(Yii::t('app.msg', 'An error occurred while confirming'));
34
                }
35
                return;
36
            }
37
        }
38
39
        throw new BadRequestHttpException(Yii::t('app.msg', 'Invalid token for activate account'));
40
    }
41
42
    /**
43
     * Sends an email with a link, for confirm the email
44
     *
45
     * @throws UserException
46
     */
47
    public function sendEmail(User $user): void
48
    {
49
        if (!$this->tokenizer->validate($user->email_confirm_token)) {
50
            $user->setEmailConfirmToken($this->tokenizer->generate());
51
            $user->updateAttributes([
52
                'email_confirm_token' => $user->email_confirm_token,
53
                'date_confirm' => $user->date_confirm,
54
            ]);
55
        }
56
57
        $sent = Yii::$app->notify->sendMessage(
58
            $user->email,
59
            Yii::t('app', 'Activate Your Account'),
60
            'emailConfirmToken',
61
            ['user' => $user]
62
        );
63
64
        if (!$sent) {
65
            throw new UserException(
66
                Yii::t('app.msg', 'An error occurred while sending a message to activate account')
67
            );
68
        }
69
    }
70
}
71