Completed
Pull Request — master (#399)
by
unknown
39:22
created

PasswordRecoveryService   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 7

Test Coverage

Coverage 91.67%

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 7
dl 0
loc 53
ccs 22
cts 24
cp 0.9167
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A run() 0 34 5
1
<?php
2
3
/*
4
 * This file is part of the 2amigos/yii2-usuario project.
5
 *
6
 * (c) 2amigOS! <http://2amigos.us/>
7
 *
8
 * For the full copyright and license information, please view
9
 * the LICENSE file that was distributed with this source code.
10
 */
11
12
namespace Da\User\Service;
13
14
use Da\User\Contracts\ServiceInterface;
15
use Da\User\Factory\TokenFactory;
16
use Da\User\Model\User;
17
use Da\User\Query\UserQuery;
18
use Da\User\Traits\MailAwareTrait;
19
use Da\User\Traits\ModuleAwareTrait;
20
use Exception;
21
use Yii;
22
23
class PasswordRecoveryService implements ServiceInterface
24
{
25
    use MailAwareTrait;
26
    use ModuleAwareTrait;
27
28
    protected $query;
29
30
    protected $email;
31
    protected $mailService;
32
    protected $securityHelper;
33
34 1
    public function __construct($email, MailService $mailService, UserQuery $query)
35
    {
36 1
        $this->email = $email;
37 1
        $this->mailService = $mailService;
38 1
        $this->query = $query;
39 1
    }
40
41 1
    public function run()
42
    {
43
        try {
44 1
            Yii::$app->session->setFlash(
45 1
                'info',
46 1
                Yii::t('usuario', 'An email with instructions to create a new password has been sent to {email} if it is associated with an {appName} account. Your existing password has not been changed.', ['email' => $this->email, 'appName' => Yii::$app->name])
47 1
            );
48
49
            /** @var User $user */
50
            $user = $this->query->whereEmail($this->email)->one();
51
52 1
            if ($user === null) {
53
                throw new \RuntimeException('User not found.');
54 1
            }
55 1
56
            $token = TokenFactory::makeRecoveryToken($user->id);
57
58 1
            if (!$token) {
59
                return false;
60 1
            }
61
62
            $this->mailService->setViewParam('user', $user);
63
            $this->mailService->setViewParam('token', $token);
64 1
            if (!$this->sendMail($user)) {
65 1
                return false;
66 1
            }
67
68
            return true;
69
        } catch (Exception $e) {
70 1
            Yii::error($e->getMessage(), 'usuario');
71 1
72 1
            return false;
73
        }
74 1
    }
75
}
76