Passed
Push — main ( 7dcca1...e70bce )
by Daniel
04:22
created

UserCreationWizard   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

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