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

CreateCommand::execute()   B

Complexity

Conditions 6
Paths 10

Size

Total Lines 32
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 4
Bugs 0 Features 0
Metric Value
cc 6
eloc 20
nc 10
nop 2
dl 0
loc 32
ccs 0
cts 20
cp 0
crap 42
rs 8.9777
c 4
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace App\User\Console;
6
7
use App\Auth\AuthService;
8
use App\Auth\Form\LoginExistException;
9
use InvalidArgumentException;
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 AuthService $authService, 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
            try {
48
                $user = $this->authService->signup($login, $password);
49
            } catch (LoginExistException $exception) {
50
                $io->error($exception->getMessage());
51
                return ExitCode::DATAERR;
52
            }
53
54
            if ($isAdmin) {
55
                $userId = $user->getId();
56
57
                if ($userId === null) {
58
                    throw new InvalidArgumentException('User Id is NULL');
59
                }
60
61
                $this->manager->assign('admin', $userId);
62
            }
63
64
            $io->success('User created');
65
        } catch (Throwable $t) {
66
            $io->error($t->getMessage());
67
            return $t->getCode() ?: ExitCode::UNSPECIFIED_ERROR;
68
        }
69
        return ExitCode::OK;
70
    }
71
}
72