Completed
Pull Request — master (#47)
by
unknown
11:14
created

UserResetter::finishReset()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 16
rs 9.4285
cc 3
eloc 9
nc 3
nop 1
1
<?php
2
3
namespace Modules\User\Services;
4
5
use Modules\User\Contracts\Authentication;
6
use Modules\User\Events\UserHasBegunResetProcess;
7
use Modules\User\Exceptions\InvalidOrExpiredResetCode;
8
use Modules\User\Exceptions\UserNotFoundException;
9
use Modules\User\Repositories\UserRepository;
10
11
class UserResetter
12
{
13
    /**
14
     * @var UserRepository
15
     */
16
    private $user;
17
    /**
18
     * @var Authentication
19
     */
20
    private $auth;
21
22
    public function __construct(UserRepository $user, Authentication $auth)
23
    {
24
        $this->user = $user;
25
        $this->auth = $auth;
26
    }
27
28
    /**
29
     * Start the reset password process for given credentials (email)
30
     * @param array $credentials
31
     * @throws UserNotFoundException
32
     */
33
    public function startReset(array $credentials)
34
    {
35
        $user = $this->findUser($credentials);
36
37
        $code = $this->auth->createReminderCode($user);
38
39
        event(new UserHasBegunResetProcess($user, $code));
40
    }
41
42
    /**
43
     * Finish the reset process
44
     * @param array $data
45
     * @return mixed
46
     * @throws InvalidOrExpiredResetCode
47
     * @throws UserNotFoundException
48
     */
49
    public function finishReset(array $data)
50
    {
51
        $user = $this->user->find(array_get($data, 'userId'));
52
53
        if ($user === null) {
54
            throw new UserNotFoundException();
55
        }
56
57
        $code = array_get($data, 'code');
58
        $password = array_get($data, 'password');
59
        if (! $this->auth->completeResetPassword($user, $code, $password)) {
60
            throw new InvalidOrExpiredResetCode();
61
        }
62
63
        return $user;
64
    }
65
66
    /**
67
     * @param array $credentials
68
     * @return mixed
69
     * @throws UserNotFoundException
70
     */
71
    private function findUser(array $credentials)
72
    {
73
        $user = $this->user->findByCredentials((array) $credentials);
74
        if ($user === null) {
75
            throw new UserNotFoundException();
76
        }
77
78
        return $user;
79
    }
80
}
81