Passed
Pull Request — master (#87)
by Dmitriy
14:25 queued 11:27
created

UserService   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Test Coverage

Coverage 85%

Importance

Changes 0
Metric Value
eloc 21
dl 0
loc 53
ccs 17
cts 20
cp 0.85
rs 10
c 0
b 0
f 0
wmc 6

3 Methods

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