UserService::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 3
c 2
b 0
f 0
dl 0
loc 8
ccs 4
cts 4
cp 1
rs 10
cc 1
nc 1
nop 3
crap 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 App\Queue\UserLoggedInMessage;
10
use Yiisoft\Auth\IdentityInterface;
11
use Yiisoft\Auth\IdentityRepositoryInterface;
12
use Yiisoft\User\CurrentUser;
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 InvalidConfigException
37
     * @throws BadRequestException
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 UserLoggedInMessage($identity->getId(), time());
60 1
        $this->queueFactory->get(LoggingAuthorizationHandler::CHANNEL)->push($queueMessage);
61
62 1
        return $identity;
63
    }
64
65 1
    public function logout(User $user): void
66
    {
67 1
        $user->resetToken();
68 1
        $this->identityRepository->save($user);
69
    }
70
}
71