Passed
Push — master ( 2c5fc5...ec65bd )
by Rustam
05:04 queued 02:32
created

UserService::logout()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 2
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace App\User;
6
7
use App\Exception\BadRequestException;
8
use Yiisoft\Auth\IdentityInterface;
9
use Yiisoft\Auth\IdentityRepositoryInterface;
10
use Yiisoft\User\CurrentUser;
11
12
final class UserService
13
{
14
    private IdentityRepositoryInterface $identityRepository;
15
    private CurrentUser $currentUser;
16
17 2
    public function __construct(CurrentUser $currentUser, IdentityRepositoryInterface $identityRepository)
18
    {
19 2
        $this->currentUser = $currentUser;
20 2
        $this->identityRepository = $identityRepository;
21
    }
22
23
    /**
24
     * @param string $login
25
     * @param string $password
26
     *
27
     * @throws BadRequestException
28
     */
29 1
    public function login(string $login, string $password): IdentityInterface
30
    {
31 1
        $identity = $this->identityRepository->findByLogin($login);
32 1
        if ($identity === null) {
33
            throw new BadRequestException('No such user.');
34
        }
35
36 1
        if (!$identity->validatePassword($password)) {
37
            throw new BadRequestException('Invalid password.');
38
        }
39
40 1
        if (!$this->currentUser->login($identity)) {
41
            throw new BadRequestException();
42
        }
43
44 1
        $identity->resetToken();
45 1
        $this->identityRepository->save($identity);
46 1
        return $identity;
47
    }
48
49 1
    public function logout(User $user): void
50
    {
51 1
        $user->resetToken();
52 1
        $this->identityRepository->save($user);
53
    }
54
}
55