Skip to content

Commit d034738

Browse files
authored
Merge pull request #29 from sumocoders/create-user-command
Add console command to add user
2 parents 3b2fcec + 9064039 commit d034738

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace App\Command\User;
6+
7+
use App\Message\User\CreateUser;
8+
use Symfony\Component\Console\Attribute\AsCommand;
9+
use Symfony\Component\Console\Command\Command;
10+
use Symfony\Component\Console\Input\InputArgument;
11+
use Symfony\Component\Console\Input\InputInterface;
12+
use Symfony\Component\Console\Output\OutputInterface;
13+
use Symfony\Component\Console\Style\SymfonyStyle;
14+
use Symfony\Component\Messenger\MessageBusInterface;
15+
use Symfony\Component\Validator\Validator\ValidatorInterface;
16+
17+
#[AsCommand(name: 'app:create-user', description: 'Hello PhpStorm')]
18+
class CreateUserCommand extends Command
19+
{
20+
public function __construct(
21+
private readonly MessageBusInterface $messageBus,
22+
private readonly ValidatorInterface $validator,
23+
) {
24+
parent::__construct();
25+
}
26+
27+
protected function execute(InputInterface $input, OutputInterface $output): int
28+
{
29+
$io = new SymfonyStyle($input, $output);
30+
31+
$message = new CreateUser();
32+
$message->email = $input->getArgument('email');
33+
$message->roles = $input->getArgument('roles');
34+
35+
$constraints = $this->validator->validate($message);
36+
if ($constraints->count() > 0) {
37+
foreach ($constraints as $constraint) {
38+
$io->error($constraint->getPropertyPath() . ': ' . $constraint->getMessage());
39+
}
40+
41+
return Command::FAILURE;
42+
}
43+
44+
$this->messageBus->dispatch($message);
45+
46+
$io->success('User created, an email has been sent to the user.');
47+
48+
return Command::SUCCESS;
49+
}
50+
51+
protected function configure(): void
52+
{
53+
$this->addArgument(
54+
'email',
55+
InputArgument::REQUIRED,
56+
'The email of the user'
57+
);
58+
$this->addArgument(
59+
'roles',
60+
InputArgument::OPTIONAL | InputArgument::IS_ARRAY,
61+
'The roles of the user',
62+
['ROLE_USER']
63+
);
64+
}
65+
}

0 commit comments

Comments
 (0)