Passed
Pull Request — master (#408)
by Wilmer
03:58
created

AuthService::logout()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

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