Passed
Push — master ( 62cbf8...9454ef )
by Evgeniy
04:00
created

AuthService::signup()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 2
eloc 5
c 1
b 0
f 1
nc 2
nop 2
dl 0
loc 10
ccs 0
cts 6
cp 0
crap 6
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace App\Auth;
6
7
use App\User\User;
8
use App\User\UserRepository;
9
use InvalidArgumentException;
10
use Throwable;
11
use Yiisoft\User\CurrentUser;
12
13
final class AuthService
14
{
15
    private CurrentUser $currentUser;
16
    private UserRepository $userRepository;
17
    private IdentityRepository $identityRepository;
18
19
    public function __construct(
20
        CurrentUser $currentUser,
21
        UserRepository $userRepository,
22
        IdentityRepository $identityRepository,
23
    ) {
24
        $this->currentUser = $currentUser;
25
        $this->userRepository = $userRepository;
26
        $this->identityRepository = $identityRepository;
27
    }
28
29
    public function login(string $login, string $password, bool $rememberMe = false): bool
30
    {
31
        $user = $this->userRepository->findByLoginWithAuthIdentity($login);
32
33
        if ($user === null || !$user->validatePassword($password)) {
34
            throw new InvalidArgumentException('Invalid login or password.');
35
        }
36
37
        $identity = $user->getIdentity();
38
        $identity->setShouldLoginByCookie($rememberMe);
39
40
        return $this->currentUser->login($identity);
41
    }
42
43
    /**
44
     * @throws Throwable
45
     */
46
    public function logout(): bool
47
    {
48
        $identity = $this->currentUser->getIdentity();
49
50
        if ($identity instanceof Identity) {
51
            $identity->regenerateCookieLoginKey();
52
            $this->identityRepository->save($identity);
53
        }
54
55
        return $this->currentUser->logout();
56
    }
57
58
    /**
59
     * @throws Throwable
60
     */
61
    public function signup(string $login, string $password): void
62
    {
63
        $user = $this->userRepository->findByLogin($login);
64
65
        if ($user !== null) {
66
            throw new InvalidArgumentException('Unable to register user with such login.');
67
        }
68
69
        $user = new User($login, $password);
70
        $this->userRepository->save($user);
71
    }
72
73
    public function isGuest(): bool
74
    {
75
        return $this->currentUser->isGuest();
76
    }
77
}
78