Test Failed
Pull Request — master (#494)
by
unknown
03:32
created

CreateCommand   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 30
dl 0
loc 54
rs 10
c 0
b 0
f 0
wmc 7

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 1
A configure() 0 8 1
A execute() 0 28 5
1
<?php
2
3
declare(strict_types=1);
4
5
namespace App\Console\User;
6
7
use App\Modules\User\User;
8
use App\Modules\User\UserRepository;
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
    private Manager $manager;
22
    private UserRepository $userRepository;
23
24
    protected static $defaultName = 'user/create';
25
26
    public function __construct(
27
        Manager $manager,
28
        UserRepository $userRepository
29
    ) {
30
        $this->manager = $manager;
31
        $this->userRepository = $userRepository;
32
        parent::__construct();
33
    }
34
35
    public function configure(): void
36
    {
37
        $this
38
            ->setDescription('Creates a user')
39
            ->setHelp('This command allows you to create a user')
40
            ->addArgument('login', InputArgument::REQUIRED, 'Login')
41
            ->addArgument('password', InputArgument::REQUIRED, 'Password')
42
            ->addArgument('isAdmin', InputArgument::OPTIONAL, 'Create user as admin');
43
    }
44
45
    protected function execute(InputInterface $input, OutputInterface $output): int
46
    {
47
        $io = new SymfonyStyle($input, $output);
48
49
        $login = $input->getArgument('login');
50
        $password = $input->getArgument('password');
51
        $isAdmin = (bool)$input->getArgument('isAdmin');
52
53
        $user = new User($login, $password);
54
        try {
55
            $this->userRepository->save($user);
56
57
            if ($isAdmin) {
58
                $userId = $user->getId();
59
60
                if ($userId === null) {
61
                    throw new InvalidArgumentException('User Id is NULL');
62
                }
63
64
                $this->manager->assign('admin', $userId);
65
            }
66
67
            $io->success('User created');
68
        } catch (Throwable $t) {
69
            $io->error($t->getMessage());
70
            return $t->getCode() ?: ExitCode::UNSPECIFIED_ERROR;
71
        }
72
        return ExitCode::OK;
73
    }
74
}
75