Passed
Pull Request — master (#97)
by
unknown
02:51
created

UserService   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 60
Duplicated Lines 0 %

Test Coverage

Coverage 86.36%

Importance

Changes 5
Bugs 1 Features 0
Metric Value
wmc 6
eloc 24
c 5
b 1
f 0
dl 0
loc 60
ccs 19
cts 22
cp 0.8636
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A logout() 0 4 1
A login() 0 29 4
A __construct() 0 8 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace App\User;
6
7
use App\Exception\BadRequestException;
8
use App\Queue\LoggingAuthorizationHandler;
9
use Yiisoft\Auth\IdentityInterface;
10
use Yiisoft\Auth\IdentityRepositoryInterface;
11
use Yiisoft\User\CurrentUser;
12
use Yiisoft\Yii\Queue\Message\Message as QueueMessage;
13
use Yiisoft\Yii\Queue\QueueFactoryInterface;
14
use Yiisoft\Definitions\Exception\InvalidConfigException;
15
16
final class UserService
17
{
18
    private IdentityRepositoryInterface $identityRepository;
19
    private CurrentUser $currentUser;
20
    private QueueFactoryInterface $queueFactory;
21
22 2
    public function __construct(
23
        CurrentUser $currentUser,
24
        IdentityRepositoryInterface $identityRepository,
25
        QueueFactoryInterface $queueFactory
26
    ) {
27 2
        $this->currentUser = $currentUser;
28 2
        $this->identityRepository = $identityRepository;
29 2
        $this->queueFactory = $queueFactory;
30
    }
31
32
    /**
33
     * @param string $login
34
     * @param string $password
35
     *
36
     * @throws BadRequestException
37
     * @throws InvalidConfigException
38
     *
39
     * @return IdentityInterface
40
     */
41 1
    public function login(string $login, string $password): IdentityInterface
42
    {
43 1
        $identity = $this->identityRepository->findByLogin($login);
44 1
        if ($identity === null) {
45
            throw new BadRequestException('No such user.');
46
        }
47
48 1
        if (!$identity->validatePassword($password)) {
49
            throw new BadRequestException('Invalid password.');
50
        }
51
52 1
        if (!$this->currentUser->login($identity)) {
53
            throw new BadRequestException();
54
        }
55
56 1
        $identity->resetToken();
57 1
        $this->identityRepository->save($identity);
58
59 1
        $queueMessage = new QueueMessage(
60
            LoggingAuthorizationHandler::NAME,
61
            [
62 1
                'id' => $identity->getId(),
63 1
                'time' => time(),
64
            ]
65
        );
66
67 1
        $this->queueFactory->get(LoggingAuthorizationHandler::CHANNEL)->push($queueMessage);
68
69 1
        return $identity;
70
    }
71
72 1
    public function logout(User $user): void
73
    {
74 1
        $user->resetToken();
75 1
        $this->identityRepository->save($user);
76
    }
77
}
78