Passed
Pull Request — master (#87)
by Dmitriy
02:45
created

UserService   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Test Coverage

Coverage 82.35%

Importance

Changes 0
Metric Value
eloc 17
c 0
b 0
f 0
dl 0
loc 41
ccs 14
cts 17
cp 0.8235
rs 10
wmc 6

3 Methods

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