Completed
Pull Request — master (#411)
by
unknown
02:03
created

PasswordRecoveryService::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 5
cts 5
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 3
crap 1
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
45
            /** @var User $user */
46 1
            $user = $this->query->whereEmail($this->email)->one();
47
48 1
            if ($user === null) {
49 1
                Yii::$app->session->setFlash('error', Yii::t('usuario', 'User not found.'));
50 1
                return false;
51
            }
52
53 1
            $token = TokenFactory::makeRecoveryToken($user->id);
54
55 1
            if (!$token) {
56
                return false;
57
            }
58
59 1
            $this->mailService->setViewParam('user', $user);
60 1
            $this->mailService->setViewParam('token', $token);
61 1
            if (!$this->sendMail($user)) {
62
                return false;
63
            }
64
65 1
            if ($this->getModule()->enableFlashMessages == true) {
66 1
                Yii::$app->session->setFlash(
67 1
                    'info',
68 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])
69
                );
70
            }
71 1
            return true;
72
        } catch (Exception $e) {
73
            Yii::error($e->getMessage(), 'usuario');
74
75
            return false;
76
        }
77
    }
78
}
79