CreateUserCommand::execute()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 33
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 24
c 1
b 0
f 0
nc 2
nop 2
dl 0
loc 33
rs 9.536
1
<?php
2
3
namespace App\Command;
4
5
use App\Document\User;
6
use Doctrine\ODM\MongoDB\DocumentManager;
7
use Symfony\Component\Console\Command\Command;
8
use Symfony\Component\Console\Input\InputInterface;
9
use Symfony\Component\Console\Output\OutputInterface;
10
use Symfony\Component\Console\Question\ChoiceQuestion;
11
use Symfony\Component\Console\Style\SymfonyStyle;
12
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
13
use Symfony\Component\Validator\Validator\ValidatorInterface;
14
15
class CreateUserCommand extends Command
16
{
17
    protected $validator;
18
19
    private $passwordEncoder;
20
    private $manager;
21
22
    public function __construct(UserPasswordEncoderInterface $passwordEncoder, DocumentManager $manager, ValidatorInterface $validator)
23
    {
24
        $this->passwordEncoder = $passwordEncoder;
25
        $this->manager = $manager;
26
        $this->validator = $validator;
27
        parent::__construct();
28
    }
29
30
    protected function configure()
31
    {
32
        $this
33
            ->setName('app:create-user')
34
            ->setDescription('Creates a new user.')
35
            ->setHelp('This command allows you to create a user');
36
    }
37
38
    protected function execute(InputInterface $input, OutputInterface $output)
39
    {
40
        $io = new SymfonyStyle($input, $output);
41
42
        $io->title('Create a new user');
43
44
        $username = $io->ask('Please enter the username');
45
        $email = $io->ask('Please enter the email');
46
        $fullName = $io->ask('Please enter the full name');
47
        $password = $io->askHidden('What is the password?');
48
49
        $helper = $this->getHelper('question');
50
        $question = new ChoiceQuestion(
51
            'Select User role',
52
            [User::ROLE_USER, User::ROLE_MANAGER, User::ROLE_ADMIN],
53
            User::ROLE_USER
54
        );
55
        $question->setErrorMessage('Role %s is invalid.');
56
57
        $role = $helper->ask($input, $output, $question);
58
59
        $user = new User();
60
        $user
61
            ->setUsername($username)
62
            ->setEmail($email)
63
            ->setFullName($fullName)
64
            ->setRole($role)
65
            ->setPassword($this->passwordEncoder->encodePassword($user, $password));
66
67
        if ($io->confirm('Create this user ?')) {
68
            $this->manager->persist($user);
69
            $this->manager->flush();
70
            $io->success('User created');
71
        }
72
    }
73
}
74