UsernameResolver   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 8
eloc 14
dl 0
loc 38
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A isValidUsername() 0 3 2
A __construct() 0 4 1
A resolve() 0 22 5
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Minepic\Resolvers;
6
7
use Minepic\Cache\UserNotFoundCache;
8
use Minepic\Helpers\UserDataValidator;
9
use Minepic\Minecraft\MojangClient;
10
use Minepic\Repositories\AccountRepository;
11
12
class UsernameResolver
13
{
14
    public function __construct(
15
        private AccountRepository $accountRepository,
16
        private MojangClient $mojangClient
17
    ) {
18
    }
19
20
    /**
21
     * @throws \Exception
22
     */
23
    public function resolve(string $username): ?string
24
    {
25
        if (!$this->isValidUsername($username)) {
26
            return null;
27
        }
28
29
        $account = $this->accountRepository->findLastUpdatedByUsername($username);
30
        if ($account !== null) {
31
            return $account->uuid;
32
        }
33
34
        if (!UserNotFoundCache::has($username)) {
35
            try {
36
                $mojangAccount = $this->mojangClient->sendUsernameInfoRequest($username);
37
38
                return $mojangAccount->getUuid();
39
            } catch (\Throwable $exception) {
40
                UserNotFoundCache::add($username);
41
            }
42
        }
43
44
        return null;
45
    }
46
47
    private function isValidUsername(string $username): bool
48
    {
49
        return UserDataValidator::isValidUsername($username) || UserDataValidator::isValidEmail($username);
50
    }
51
}
52