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

AuthService   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 24
c 1
b 0
f 1
dl 0
loc 63
ccs 0
cts 27
cp 0
rs 10
wmc 9

5 Methods

Rating   Name   Duplication   Size   Complexity  
A logout() 0 10 2
A login() 0 12 3
A isGuest() 0 3 1
A __construct() 0 8 1
A signup() 0 10 2
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