Test Failed
Pull Request — master (#476)
by
unknown
03:13
created

CreateCommand::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 3
Bugs 1 Features 0
Metric Value
cc 1
eloc 1
nc 1
nop 2
dl 0
loc 3
ccs 0
cts 0
cp 0
crap 2
rs 10
c 3
b 1
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace App\User\Console;
6
7
use App\User\SignupService;
8
use App\User\UserLoginException;
9
use App\User\UserPasswordException;
10
use Symfony\Component\Console\Command\Command;
11
use Symfony\Component\Console\Input\InputArgument;
12
use Symfony\Component\Console\Input\InputInterface;
13
use Symfony\Component\Console\Output\OutputInterface;
14
use Symfony\Component\Console\Style\SymfonyStyle;
15
use Throwable;
16
use Yiisoft\Rbac\Manager;
17
use Yiisoft\Yii\Console\ExitCode;
18
19
final class CreateCommand extends Command
20
{
21
    protected static $defaultName = 'user/create';
22
23
    public function __construct(private SignupService $signupService, private Manager $manager)
24
    {
25
        parent::__construct();
26
    }
27
28
    protected function configure(): void
29
    {
30
        $this
31
            ->setDescription('Creates a user')
32
            ->setHelp('This command allows you to create a user')
33
            ->addArgument('login', InputArgument::REQUIRED, 'Login')
34
            ->addArgument('password', InputArgument::REQUIRED, 'Password')
35
            ->addArgument('isAdmin', InputArgument::OPTIONAL, 'Create user as admin');
36
    }
37
38
    protected function execute(InputInterface $input, OutputInterface $output): int
39
    {
40
        $io = new SymfonyStyle($input, $output);
41
42
        $login = $input->getArgument('login');
43
        $password = $input->getArgument('password');
44
        $isAdmin = (bool)$input->getArgument('isAdmin');
45
46
        try {
47
            $user = $this->signupService
48
                ->setLogin($login)
49
                ->setPassword($password)
50
                ->signup();
51
52
            if ($isAdmin) {
53
                $userId = $user->getId();
54
55
                if ($userId === null) {
56
                    throw new \LogicException('User Id is NULL');
57
                }
58
59
                $this->manager->assign('admin', $userId);
60
            }
61
62
            $io->success('User created');
63
        } catch (UserLoginException|UserPasswordException $exception) {
64
            $io->error($exception::class . ' ' . $exception->getMessage());
65
            return ExitCode::DATAERR;
66
        } catch (Throwable $t) {
67
            $io->error($t->getMessage());
68
            return $t->getCode() ?: ExitCode::UNSPECIFIED_ERROR;
69
        }
70
        return ExitCode::OK;
71
    }
72
}
73