|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace App\User\Console; |
|
6
|
|
|
|
|
7
|
|
|
use App\Auth\Form\SignupForm; |
|
8
|
|
|
use Symfony\Component\Console\Command\Command; |
|
9
|
|
|
use Symfony\Component\Console\Input\InputArgument; |
|
10
|
|
|
use Symfony\Component\Console\Input\InputInterface; |
|
11
|
|
|
use Symfony\Component\Console\Output\OutputInterface; |
|
12
|
|
|
use Symfony\Component\Console\Style\SymfonyStyle; |
|
13
|
|
|
use Throwable; |
|
14
|
|
|
use Yiisoft\Rbac\Manager; |
|
15
|
|
|
use Yiisoft\Yii\Console\ExitCode; |
|
16
|
|
|
|
|
17
|
|
|
final class CreateCommand extends Command |
|
18
|
|
|
{ |
|
19
|
|
|
protected static $defaultName = 'user/create'; |
|
20
|
|
|
|
|
21
|
|
|
public function __construct(private SignupForm $signupForm, private Manager $manager) |
|
22
|
|
|
{ |
|
23
|
|
|
parent::__construct(); |
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
|
|
protected function configure(): void |
|
27
|
|
|
{ |
|
28
|
|
|
$this |
|
29
|
|
|
->setDescription('Creates a user') |
|
30
|
|
|
->setHelp('This command allows you to create a user') |
|
31
|
|
|
->addArgument('login', InputArgument::REQUIRED, 'Login') |
|
32
|
|
|
->addArgument('password', InputArgument::REQUIRED, 'Password') |
|
33
|
|
|
->addArgument('isAdmin', InputArgument::OPTIONAL, 'Create user as admin'); |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
protected function execute(InputInterface $input, OutputInterface $output): int |
|
37
|
|
|
{ |
|
38
|
|
|
$io = new SymfonyStyle($input, $output); |
|
39
|
|
|
|
|
40
|
|
|
$login = (string)$input->getArgument('login'); |
|
41
|
|
|
$password = (string)$input->getArgument('password'); |
|
42
|
|
|
$isAdmin = (bool)$input->getArgument('isAdmin'); |
|
43
|
|
|
|
|
44
|
|
|
$this->signupForm->load([ |
|
45
|
|
|
'login' => $login, |
|
46
|
|
|
'password' => $password, |
|
47
|
|
|
'passwordVerify' => $password, |
|
48
|
|
|
], ''); |
|
49
|
|
|
|
|
50
|
|
|
try { |
|
51
|
|
|
$user = $this->signupForm->signup(); |
|
52
|
|
|
} catch (Throwable $t) { |
|
53
|
|
|
$io->error($t->getMessage() . ' ' . $t->getFile() . ' ' . $t->getLine()); |
|
54
|
|
|
return $t->getCode() ?: ExitCode::UNSPECIFIED_ERROR; |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
if ($user === false) { |
|
58
|
|
|
$errors = $this->signupForm->getFormErrors()->getFirstErrors(); |
|
59
|
|
|
array_walk($errors, fn($error, $attribute) => $io->error("$attribute: $error")); |
|
60
|
|
|
return ExitCode::DATAERR; |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
if ($isAdmin) { |
|
64
|
|
|
$userId = $user->getId(); |
|
65
|
|
|
if ($userId === null) { |
|
66
|
|
|
throw new \LogicException('User Id is NULL'); |
|
67
|
|
|
} |
|
68
|
|
|
$this->manager->assign('admin', $userId); |
|
69
|
|
|
} |
|
70
|
|
|
$io->success('User created'); |
|
71
|
|
|
return ExitCode::OK; |
|
72
|
|
|
} |
|
73
|
|
|
} |
|
74
|
|
|
|