Passed
Push — main ( 1d1c5b...83bc52 )
by Daniel
04:23
created

UserCreationWizard::create()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 41
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 23
c 1
b 0
f 0
dl 0
loc 41
ccs 18
cts 18
cp 1
rs 9.552
cc 4
nc 3
nop 2
crap 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Uxmp\Core\Component\Cli\Wizard;
6
7
use Ahc\Cli\IO\Interactor;
8
use InvalidArgumentException;
9
use Uxmp\Core\Component\User\PasswordVerificator;
10
use Uxmp\Core\Component\User\UserCreatorInterface;
11
use Uxmp\Core\Orm\Repository\UserRepositoryInterface;
12
use function mb_strlen;
13
14
/**
15
 * Leads the user through the user creation process on the cli
16
 */
17
final class UserCreationWizard implements UserCreationWizardInterface
18
{
19
    private const PASSWORD_RETRIES = 2;
20
21 4
    public function __construct(
22
        private readonly UserRepositoryInterface $userRepository,
0 ignored issues
show
Bug introduced by
A parse error occurred: Syntax error, unexpected T_STRING, expecting T_VARIABLE on line 22 at column 25
Loading history...
23
        private readonly UserCreatorInterface $userCreator,
24
    ) {
25
    }
26
27 4
    public function create(
28
        Interactor $io,
29
        string $username,
30
    ): void {
31 4
        $user = $this->userRepository->findOneBy([
32
            'name' => $username,
33
        ]);
34
35 4
        if ($user !== null) {
36 1
            $io->error('A user with that name already exists', true);
37 1
            return;
38
        }
39
40 3
        $validator = function ($password): string {
41 2
            $password = trim((string) $password);
42 2
            if (mb_strlen($password) < PasswordVerificator::PASSWORD_MIN_LENGTH) {
43 1
                throw new InvalidArgumentException('Password too short');
44
            }
45
46 1
            return $password;
47
        };
48
49 3
        $password = $io->promptHidden('Password', $validator, self::PASSWORD_RETRIES);
50
51 2
        if ($password === '') {
52 1
            $io->error('Too many retries - aborting', true);
53 1
            return;
54
        }
55
56 1
        $user = $this->userCreator->create(
57
            $username,
58
            $password
59
        );
60
61 1
        $io->info(
62 1
            sprintf(
63
                'Created user `%s` with id `%d`',
64
                $username,
65 1
                $user->getId()
66
            ),
67
            true
68
        );
69
    }
70
}
71