Completed
Push — master ( d861b1...95c183 )
by Jeroen
22:16 queued 07:16
created

AdminBundle/Command/CreateUserCommand.php (10 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\EntityManagerInterface;
6
use FOS\UserBundle\Model\GroupManagerInterface;
7
use Kunstmaan\AdminBundle\Entity\BaseUser;
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
0 ignored issues
show
Deprecated Code introduced by
The class Symfony\Bundle\Framework...d\ContainerAwareCommand has been deprecated with message: since Symfony 4.2, use {@see Command} instead.

This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the type will be removed from the class and what other constant to use instead.

Loading history...
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
    public function __construct(/* EntityManagerInterface */ $em = null, GroupManagerInterface $groupManager = null, $userClassname = null, $defaultLocale = null)
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);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
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
    protected function initialize(InputInterface $input, OutputInterface $output)
101
    {
102
        $this->groups = $this->getGroups();
103
    }
104
105
    /**
106
     * Executes the current command.
107
     *
108
     * @param InputInterface  $input  The input
109
     * @param OutputInterface $output The output
110
     *
111
     * @return int
112
     */
113
    protected function execute(InputInterface $input, OutputInterface $output)
114
    {
115
        if (null === $this->em) {
116
            $this->em = $this->getContainer()->get('doctrine.orm.entity_manager');
117
            $this->groupManager = $this->getContainer()->get('fos_user.group_manager');
118
            $this->userClassname = $this->getContainer()->getParameter('fos_user.model.user.class');
119
            $this->defaultLocale = $this->getContainer()->getParameter('kunstmaan_admin.default_admin_locale');
120
        }
121
122
        $username = $input->getArgument('username');
123
        $email = $input->getArgument('email');
124
        $password = $input->getArgument('password');
125
        $locale = $input->getArgument('locale');
126
        $superAdmin = $input->getOption('super-admin');
127
        $inactive = $input->getOption('inactive');
128
        $groupOption = $input->getOption('group');
129
130
        if (null === $locale) {
131
            $locale = $this->defaultLocale;
132
        }
133
        $command = $this->getApplication()->find('fos:user:create');
134
        $arguments = array(
135
            'command' => 'fos:user:create',
136
            'username' => $username,
137
            'email' => $email,
138
            'password' => $password,
139
            '--super-admin' => $superAdmin,
140
            '--inactive' => $inactive,
141
        );
142
143
        $input = new ArrayInput($arguments);
144
        $command->run($input, $output);
145
146
        // Fetch user that was just created
147
        /** @var BaseUser $user */
148
        $user = $this->em->getRepository($this->userClassname)->findOneBy(array('username' => $username));
149
150
        $user->setCreatedBy('kuma:user:create command');
151
        $this->em->flush();
152
153
        // Attach groups
154
        $groupOutput = [];
155
156
        foreach (explode(',', $groupOption) as $groupId) {
157
            if ((int) $groupId === 0) {
158
                foreach ($this->groups as $value) {
159
                    if ($groupId === $value->getName()) {
160
                        $group = $value;
161
162
                        break;
163
                    }
164
                }
165
            } else {
166
                $group = $this->groups[$groupId];
167
            }
168
169
            if (isset($group) && $group instanceof Group) {
170
                $groupOutput[] = $group->getName();
171
                $user->getGroups()->add($group);
172
            } else {
173
                throw new \RuntimeException('The selected group(s) can\'t be found.');
174
            }
175
        }
176
177
        // Set admin interface locale and enable password changed
178
        $user->setAdminLocale($locale);
179
        $user->setPasswordChanged(true);
180
181
        // Persist
182
        $this->em->persist($user);
183
        $this->em->flush();
184
185
        $output->writeln(sprintf('Added user <comment>%s</comment> to groups <comment>%s</comment>', $input->getArgument('username'), implode(',', $groupOutput)));
186
187
        return 0;
188
    }
189
190
    /**
191
     * Interacts with the user.
192
     *
193
     * @param InputInterface  $input  The input
194
     * @param OutputInterface $output The output
195
     *
196
     * @throws \InvalidArgumentException
197
     */
198
    protected function interact(InputInterface $input, OutputInterface $output)
199
    {
200 View Code Duplication
        if (!$input->getArgument('username')) {
0 ignored issues
show
This code seems to be duplicated across 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...
201
            $question = new Question('Please choose a username:');
202
            $question->setValidator(function ($username) {
203
                if (null === $username) {
204
                    throw new \InvalidArgumentException('Username can not be empty');
205
                }
206
207
                return $username;
208
            });
209
            $username = $this->getHelper('question')->ask(
0 ignored issues
show
It seems like you code against a concrete implementation and not the interface Symfony\Component\Console\Helper\HelperInterface as the method ask() does only exist in the following implementations of said interface: Sensio\Bundle\GeneratorB...d\Helper\QuestionHelper, Symfony\Component\Console\Helper\QuestionHelper, Symfony\Component\Consol...r\SymfonyQuestionHelper.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
210
                $input,
211
                $output,
212
                $question
213
            );
214
            $input->setArgument('username', $username);
215
        }
216
217 View Code Duplication
        if (!$input->getArgument('email')) {
0 ignored issues
show
This code seems to be duplicated across 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...
218
            $question = new Question('Please choose an email:');
219
            $question->setValidator(function ($email) {
220
                if (null === $email) {
221
                    throw new \InvalidArgumentException('Email can not be empty');
222
                }
223
224
                return $email;
225
            });
226
            $email = $this->getHelper('question')->ask(
0 ignored issues
show
It seems like you code against a concrete implementation and not the interface Symfony\Component\Console\Helper\HelperInterface as the method ask() does only exist in the following implementations of said interface: Sensio\Bundle\GeneratorB...d\Helper\QuestionHelper, Symfony\Component\Console\Helper\QuestionHelper, Symfony\Component\Consol...r\SymfonyQuestionHelper.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
227
                $input,
228
                $output,
229
                $question
230
            );
231
            $input->setArgument('email', $email);
232
        }
233
234
        if (!$input->getArgument('password')) {
235
            $question = new Question('Please choose a password:');
236
            $question->setHidden(true);
237
            $question->setHiddenFallback(false);
238
            $question->setValidator(function ($password) {
239
                if (null === $password) {
240
                    throw new \InvalidArgumentException('Password can not be empty');
241
                }
242
243
                return $password;
244
            });
245
            $password = $this->getHelper('question')->ask(
0 ignored issues
show
It seems like you code against a concrete implementation and not the interface Symfony\Component\Console\Helper\HelperInterface as the method ask() does only exist in the following implementations of said interface: Sensio\Bundle\GeneratorB...d\Helper\QuestionHelper, Symfony\Component\Console\Helper\QuestionHelper, Symfony\Component\Consol...r\SymfonyQuestionHelper.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
246
                $input,
247
                $output,
248
                $question
249
            );
250
251
            $input->setArgument('password', $password);
252
        }
253
254
        if (!$input->getArgument('locale')) {
255
            $locale = $this->getHelper('question')->ask(
0 ignored issues
show
It seems like you code against a concrete implementation and not the interface Symfony\Component\Console\Helper\HelperInterface as the method ask() does only exist in the following implementations of said interface: Sensio\Bundle\GeneratorB...d\Helper\QuestionHelper, Symfony\Component\Console\Helper\QuestionHelper, Symfony\Component\Consol...r\SymfonyQuestionHelper.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
256
                $input,
257
                $output,
258
                new Question('Please enter the locale (or leave empty for default admin locale):')
259
            );
260
            $input->setArgument('locale', $locale);
261
        }
262
263
        if (!$input->getOption('group')) {
264
            $question = new ChoiceQuestion(
265
                'Please enter the group(s) the user should be a member of (multiple possible, separated by comma):',
266
                $this->groups,
267
                ''
268
            );
269
            $question->setMultiselect(true);
270
            $question->setValidator(function ($groupsInput) {
271
                if (!$this->groups) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->groups of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
272
                    throw new \RuntimeException('No user group(s) could be found');
273
                }
274
275
                // Validate that the chosen group options exist in the available groups
276
                $groupNames = array_unique(explode(',', $groupsInput));
277
                if (\count(array_intersect_key(array_flip($groupNames), $this->groups)) !== \count($groupNames)) {
278
                    throw new InvalidArgumentException('You have chosen non existing group(s)');
279
                }
280
281
                if ($groupsInput === '') {
282
                    throw new \RuntimeException('Group(s) must be of type integer and can not be empty');
283
                }
284
285
                return $groupsInput;
286
            });
287
288
            // Group has to be imploded because $input->setOption expects a string
289
            $groups = $this->getHelper('question')->ask($input, $output, $question);
0 ignored issues
show
It seems like you code against a concrete implementation and not the interface Symfony\Component\Console\Helper\HelperInterface as the method ask() does only exist in the following implementations of said interface: Sensio\Bundle\GeneratorB...d\Helper\QuestionHelper, Symfony\Component\Console\Helper\QuestionHelper, Symfony\Component\Consol...r\SymfonyQuestionHelper.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
290
291
            $input->setOption('group', $groups);
292
        }
293
    }
294
295
    private function getGroups()
296
    {
297
        $groups = $this->groupManager->findGroups();
298
299
        // reindexing the array, using the db id as the key
300
        $newGroups = [];
301
        foreach ($groups as $group) {
302
            $newGroups[$group->getId()] = $group;
303
        }
304
305
        return $newGroups;
306
    }
307
}
308