Completed
Pull Request — master (#2102)
by Kevin
14:50
created

AdminBundle/Command/CreateUserCommand.php (2 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
namespace Kunstmaan\AdminBundle\Command;
4
5
use Doctrine\ORM\EntityManager;
6
use Doctrine\ORM\EntityManagerInterface;
7
use FOS\UserBundle\Model\GroupManagerInterface;
8
use Kunstmaan\AdminBundle\Entity\Group;
9
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
10
use Symfony\Component\Console\Input\ArrayInput;
11
use Symfony\Component\Console\Input\InputArgument;
12
use Symfony\Component\Console\Input\InputInterface;
13
use Symfony\Component\Console\Input\InputOption;
14
use Symfony\Component\Console\Output\OutputInterface;
15
use Symfony\Component\Console\Question\ChoiceQuestion;
16
use Symfony\Component\Console\Question\Question;
17
use Symfony\Component\Console\Exception\InvalidArgumentException;
18
19
/**
20
 * Symfony CLI command to create a user using bin/console kuma:user:create <username_of_the_user>
21
 *
22
 * @final since 5.1
23
 * NEXT_MAJOR extend from `Command` and remove `$this->getContainer` usages
24
 */
25
class CreateUserCommand extends ContainerAwareCommand
26
{
27
    /** @var EntityManagerInterface */
28
    private $em;
29
30
    /** @var GroupManagerInterface */
31
    private $groupManager;
32
33
    /** @var string */
34
    private $userClassname;
35
36
    /** @var string */
37
    private $defaultLocale;
38
39
    /** @var array */
40
    protected $groups = [];
41
42 View Code Duplication
    public function __construct(/* EntityManagerInterface */ $em = null, GroupManagerInterface $groupManager = null, $userClassname = null, $defaultLocale = null)
0 ignored issues
show
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
43
    {
44
        parent::__construct();
45
46
        if (!$em instanceof EntityManagerInterface) {
47
            @trigger_error(sprintf('Passing a command name as the first argument of "%s" is deprecated since version symfony 3.4 and will be removed in symfony 4.0. If the command was registered by convention, make it a service instead. ', __METHOD__), E_USER_DEPRECATED);
48
49
            $this->setName(null === $em ? 'kuma:user:create' : $em);
50
51
            return;
52
        }
53
54
        $this->em = $em;
55
        $this->groupManager = $groupManager;
56
        $this->userClassname = $userClassname;
57
        $this->defaultLocale = $defaultLocale;
58
    }
59
60
    protected function configure()
61
    {
62
        parent::configure();
63
64
        $this->setName('kuma:user:create')
65
            ->setDescription('Create a user.')
66
            ->setDefinition(array(
67
                new InputArgument('username', InputArgument::REQUIRED, 'The username'),
68
                new InputArgument('email', InputArgument::REQUIRED, 'The email'),
69
                new InputArgument('password', InputArgument::REQUIRED, 'The password'),
70
                new InputArgument('locale', InputArgument::OPTIONAL, 'The locale (language)'),
71
                new InputOption('group', null, InputOption::VALUE_REQUIRED, 'The group(s) the user should belong to'),
72
                new InputOption('super-admin', null, InputOption::VALUE_NONE, 'Set the user as super admin'),
73
                new InputOption('inactive', null, InputOption::VALUE_NONE, 'Set the user as inactive'),
74
            ))
75
            ->setHelp(<<<EOT
76
The <info>kuma:user:create</info> command creates a user:
77
78
  <info>php bin/console kuma:user:create matthieu --group=Users</info>
79
80
This interactive shell will ask you for an email and then a password.
81
82
You can alternatively specify the email, password and locale and group as extra arguments:
83
84
  <info>php bin/console kuma:user:create matthieu [email protected] mypassword en --group=Users</info>
85
86
You can create a super admin via the super-admin flag:
87
88
  <info>php bin/console kuma:user:create admin --super-admin --group=Administrators</info>
89
90
You can create an inactive user (will not be able to log in):
91
92
  <info>php bin/console kuma:user:create thibault --inactive --group=Users</info>
93
94
<comment>Note:</comment> You have to specify at least one group.
95
96
EOT
97
            );
98
    }
99
100
    /**
101
     * Executes the current command.
102
     *
103
     * @param InputInterface $input The input
104
     * @param OutputInterface $output The output
105
     *
106
     * @return int
107
     */
108
    protected function execute(InputInterface $input, OutputInterface $output)
109
    {
110
        if (null === $this->em) {
111
            $this->em = $this->getContainer()->get('doctrine.orm.entity_manager');
112
            $this->groupManager = $this->getContainer()->get('fos_user.group_manager');
113
            $this->userClassname = $this->getContainer()->getParameter('fos_user.model.user.class');
114
            $this->defaultLocale = $this->getContainer()->getParameter('kunstmaan_admin.default_admin_locale');
115
        }
116
117
        $username = $input->getArgument('username');
118
        $email = $input->getArgument('email');
119
        $password = $input->getArgument('password');
120
        $locale = $input->getArgument('locale');
121
        $superAdmin = $input->getOption('super-admin');
122
        $inactive = $input->getOption('inactive');
123
        $groupOption = $input->getOption('group');
124
125
        if (null !== $locale) {
126
            $locale = $this->defaultLocale;
127
        }
128
        $command = $this->getApplication()->find('fos:user:create');
129
        $arguments = array(
130
            'command' => 'fos:user:create',
131
            'username' => $username,
132
            'email' => $email,
133
            'password' => $password,
134
            '--super-admin' => $superAdmin,
135
            '--inactive' => $inactive,
136
        );
137
138
        $input = new ArrayInput($arguments);
139
        $command->run($input, $output);
140
141
        // Fetch user that was just created
142
        $user = $this->em->getRepository($this->userClassname)->findOneBy(array('username' => $username));
143
144
        // Attach groups
145
        $groupOutput = [];
146
147
148
        foreach (explode(',', $groupOption) as $groupId) {
149
150
            if ((int)$groupId === 0) {
151
                foreach ($this->groups as $value) {
152
                    if ($groupId === $value->getName()) {
153
                        $group = $value;
154
                        break;
155
                    }
156
                }
157
            } else {
158
                $group = $this->groups[$groupId];
159
            }
160
161
            if (isset($group) && $group instanceof Group) {
162
                $groupOutput[] = $group->getName();
163
                $user->getGroups()->add($group);
164
            } else {
165
                throw new \RuntimeException(
166
                    'The selected group(s) can\'t be found.'
167
                );
168
            }
169
        }
170
171
        // Set admin interface locale and enable password changed
172
        $user->setAdminLocale($locale);
173
        $user->setPasswordChanged(true);
174
175
        // Persist
176
        $this->em->persist($user);
177
        $this->em->flush();
178
179
        $output->writeln(sprintf('Added user <comment>%s</comment> to groups <comment>%s</comment>', $input->getArgument('username'), implode(',', $groupOutput)));
180
    }
181
182
    /**
183
     * Interacts with the user.
184
     *
185
     * @param InputInterface $input The input
186
     * @param OutputInterface $output The output
187
     *
188
     * @throws \InvalidArgumentException
189
     *
190
     * @return void
191
     */
192
    protected function interact(InputInterface $input, OutputInterface $output)
193
    {
194 View Code Duplication
        if (!$input->getArgument('username')) {
195
            $question = New Question('Please choose a username:');
196
            $question->setValidator(function ($username) {
197
                if (null === $username) {
198
                    throw new \InvalidArgumentException('Username can not be empty');
199
                }
200
201
                return $username;
202
            });
203
            $username = $this->getHelper('question')->ask(
204
                $input,
205
                $output,
206
                $question
207
            );
208
            $input->setArgument('username', $username);
209
        }
210
211 View Code Duplication
        if (!$input->getArgument('email')) {
212
            $question = New Question('Please choose an email:');
213
            $question->setValidator(function ($email) {
214
                if (null === $email) {
215
                    throw new \InvalidArgumentException('Email can not be empty');
216
                }
217
218
                return $email;
219
            });
220
            $email = $this->getHelper('question')->ask(
221
                $input,
222
                $output,
223
                $question
224
            );
225
            $input->setArgument('email', $email);
226
        }
227
228
        if (!$input->getArgument('password')) {
229
230
            $question = New Question('Please choose a password:');
231
            $question->setHidden(true);
232
            $question->setHiddenFallback(false);
233
            $question->setValidator(function ($password) {
234
                if (null === $password) {
235
                    throw new \InvalidArgumentException('Password can not be empty');
236
                }
237
238
                return $password;
239
            });
240
            $password = $this->getHelper('question')->ask(
241
                $input,
242
                $output,
243
                $question
244
            );
245
246
            $input->setArgument('password', $password);
247
        }
248
249
        if (!$input->getArgument('locale')) {
250
            $locale = $this->getHelper('question')->ask(
251
                $input,
252
                $output,
253
                new Question('Please enter the locale (or leave empty for default admin locale):')
254
            );
255
            $input->setArgument('locale', $locale);
256
        }
257
258
        $this->groups = $this->groupManager->findGroups();
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->groupManager->findGroups() of type object<Traversable> is incompatible with the declared type array of property $groups.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
259
260
        // reindexing the array, using the db id as the key
261
        $newGroups = [];
262
        foreach($this->groups as $group) {
263
            $newGroups[$group->getId()] = $group;
264
        }
265
266
        $this->groups = $newGroups;
267
268
        if (!$input->getOption('group')) {
269
            $question = new ChoiceQuestion(
270
                'Please enter the group(s) the user should be a member of (multiple possible, separated by comma):',
271
                $this->groups,
272
                ''
273
            );
274
            $question->setMultiselect(true);
275
            $question->setValidator(function ($groupsInput) {
276
277
                if (!$this->groups) {
278
                    throw new \RuntimeException('No user group(s) could be found');
279
                }
280
281
                // Validate that the chosen group options exist in the available groups
282
                $groupNames = array_unique(explode(',', $groupsInput));
283
                if (count(array_intersect_key(array_flip($groupNames),$this->groups)) !== count($groupNames)) {
284
                    throw new InvalidArgumentException('You have chosen non existing group(s)');
285
                }
286
287
                if ($groupsInput === '') {
288
                    throw new \RuntimeException(
289
                        'Group(s) must be of type integer and can not be empty'
290
                    );
291
                }
292
                return $groupsInput;
293
            });
294
295
            // Group has to be imploded because $input->setOption expects a string
296
            $groups = $this->getHelper('question')->ask($input, $output, $question);
297
298
            $input->setOption('group', $groups);
299
        }
300
    }
301
}
302