Completed
Pull Request — master (#2737)
by
unknown
08:55
created

CreateUserCommand::__construct()   B

Complexity

Conditions 9
Paths 8

Size

Total Lines 33

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 90

Importance

Changes 0
Metric Value
dl 0
loc 33
ccs 0
cts 23
cp 0
rs 8.0555
c 0
b 0
f 0
cc 9
nc 8
nop 4
crap 90
1
<?php
2
3
namespace Kunstmaan\AdminBundle\Command;
4
5
use Doctrine\ORM\EntityManagerInterface;
6
use FOS\UserBundle\Model\GroupManager as FOSGroupManager;
7
use FOS\UserBundle\Model\UserManager as FOSUserManager;
8
use Kunstmaan\AdminBundle\Entity\Group;
9
use Kunstmaan\AdminBundle\Service\GroupManager;
10
use Kunstmaan\AdminBundle\Service\UserManager;
11
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
12
use Symfony\Component\Console\Exception\InvalidArgumentException;
13
use Symfony\Component\Console\Input\InputArgument;
14
use Symfony\Component\Console\Input\InputInterface;
15
use Symfony\Component\Console\Input\InputOption;
16
use Symfony\Component\Console\Output\OutputInterface;
17
use Symfony\Component\Console\Question\ChoiceQuestion;
18
use Symfony\Component\Console\Question\Question;
19
20
/**
21
 * Symfony CLI command to create a user using bin/console kuma:user:create <username_of_the_user>
22
 *
23
 * @final since 5.1
24
 * NEXT_MAJOR extend from `Command` and remove `$this->getContainer` usages
25
 */
26
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...
27
{
28
    protected static $defaultName = 'kuma:user:create';
29
30
    /** @var array */
31
    protected $groups = [];
32
    /** @var EntityManagerInterface */
33
    private $em;
34
    /** @var GroupManager */
35
    private $groupManager;
36
    /** @var UserManager */
37
    private $userManager;
38
    /** @var string */
39
    private $defaultLocale;
40
41
    public function __construct(/* EntityManagerInterface */ $em = null, /* GroupManager */ $groupManager = null, /* UserManager */ $userManager, $defaultLocale = null)
42
    {
43
        parent::__construct();
44
45
        if (!$em instanceof EntityManagerInterface) {
46
            @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...
47
48
            $this->setName(null === $em ? 'kuma:user:create' : $em);
49
50
            return;
51
        }
52
53
        if (!$groupManager instanceof GroupManager && !$groupManager instanceof FOSGroupManager) {
54
            throw new \InvalidArgumentException(sprintf('The "$groupManager" argument must be of type "%s" or type "%s"', GroupManager::class, FOSGroupManager::class));
55
        }
56
        if ($groupManager instanceof FOSGroupManager) {
57
            // NEXT_MAJOR set the groupmanager typehint to the kunstmaan groupmanager.
58
            @trigger_error(sprintf('Passing the groupmanager from FOSUserBundle as the first argument of "%s" is deprecated since KunstmaanAdminBundle 5.8 and will be removed in KunstmaanAdminBundle 6.0. Use the "%s" class instead.', __METHOD__, GroupManager::class), 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...
59
        }
60
61
        if (!$userManager instanceof UserManager && !$userManager instanceof FOSUserManager) {
62
            throw new \InvalidArgumentException(sprintf('The "$userManager" argument must be of type "%s" or type "%s"', UserManager::class, FOSUserManager::class));
63
        }
64
        if ($userManager instanceof FOSUserManager) {
65
            // NEXT_MAJOR set the usermanaged typehint to the kunstmaan usermanager.
66
            @trigger_error(sprintf('Passing the usermanager from FOSUserBundle as the first argument of "%s" is deprecated since KunstmaanAdminBundle 5.8 and will be removed in KunstmaanAdminBundle 6.0. Use the "%s" class instead.', __METHOD__, UserManager::class), 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...
67
        }
68
69
        $this->em = $em;
70
        $this->groupManager = $groupManager;
0 ignored issues
show
Documentation Bug introduced by
It seems like $groupManager can also be of type object<FOS\UserBundle\Model\GroupManager>. However, the property $groupManager is declared as type object<Kunstmaan\AdminBu...e\Service\GroupManager>. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
71
        $this->userManager = $userManager;
0 ignored issues
show
Documentation Bug introduced by
It seems like $userManager can also be of type object<FOS\UserBundle\Model\UserManager>. However, the property $userManager is declared as type object<Kunstmaan\AdminBundle\Service\UserManager>. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
72
        $this->defaultLocale = $defaultLocale;
73
    }
74
75
    protected function configure()
76
    {
77
        parent::configure();
78
79
        $this->setDescription('Create a user.')
80
            ->setDefinition([
81
                new InputArgument('username', InputArgument::REQUIRED, 'The username'),
82
                new InputArgument('email', InputArgument::REQUIRED, 'The email'),
83
                new InputArgument('password', InputArgument::REQUIRED, 'The password'),
84
                new InputArgument('locale', InputArgument::OPTIONAL, 'The locale (language)'),
85
                new InputOption('group', null, InputOption::VALUE_REQUIRED, 'The group(s) the user should belong to'),
86
                new InputOption('super-admin', null, InputOption::VALUE_NONE, 'Set the user as super admin'),
87
                new InputOption('inactive', null, InputOption::VALUE_NONE, 'Set the user as inactive'),
88
            ])
89
            ->setHelp(<<<'EOT'
90
The <info>kuma:user:create</info> command creates a user:
91
92
  <info>php bin/console kuma:user:create matthieu --group=Users</info>
93
94
This interactive shell will ask you for an email and then a password.
95
96
You can alternatively specify the email, password and locale and group as extra arguments:
97
98
  <info>php bin/console kuma:user:create matthieu [email protected] mypassword en --group=Users</info>
99
100
You can create a super admin via the super-admin flag:
101
102
  <info>php bin/console kuma:user:create admin --super-admin --group=Administrators</info>
103
104
You can create an inactive user (will not be able to log in):
105
106
  <info>php bin/console kuma:user:create thibault --inactive --group=Users</info>
107
108
<comment>Note:</comment> You have to specify at least one group.
109
110
EOT
111
            );
112
    }
113
114
    protected function initialize(InputInterface $input, OutputInterface $output)
115
    {
116
        $this->groups = $this->getGroups();
117
    }
118
119
    private function getGroups()
120
    {
121
        $groups = $this->groupManager->findGroups();
122
123
        // reindexing the array, using the db id as the key
124
        $newGroups = [];
125
        foreach ($groups as $group) {
126
            $newGroups[$group->getId()] = $group;
127
        }
128
129
        return $newGroups;
130
    }
131
132
    /**
133
     * Executes the current command.
134
     *
135
     * @param InputInterface  $input  The input
136
     * @param OutputInterface $output The output
137
     *
138
     * @return int
139
     */
140
    protected function execute(InputInterface $input, OutputInterface $output)
141
    {
142
        if (null === $this->em) {
143
            $this->em = $this->getContainer()->get('doctrine.orm.entity_manager');
144
            $this->groupManager = $this->getContainer()->get('kunstmaan_admin.group_manager');
145
            $this->userManager = $this->getContainer()->get('kunstmaan_admin.user_manager');
146
            $this->defaultLocale = $this->getContainer()->getParameter('kunstmaan_admin.default_admin_locale');
147
        }
148
149
        $username = $input->getArgument('username');
150
        $email = $input->getArgument('email');
151
        $password = $input->getArgument('password');
152
        $locale = $input->getArgument('locale');
153
        $superAdmin = $input->getOption('super-admin');
154
        $inactive = $input->getOption('inactive');
155
        $groupOption = $input->getOption('group');
156
157
        if (null === $locale) {
158
            $locale = $this->defaultLocale;
159
        }
160
161
        $user = $this->userManager->createUser();
162
        $user->setUsername($username);
163
        $user->setEmail($email);
164
        $user->setPlainPassword($password);
165
        $user->setEnabled(!((bool) $inactive));
166
        $user->setSuperAdmin((bool) $superAdmin);
167
        $this->userManager->updateUser($user);
168
169
        $output->writeln(sprintf('Created user <comment>%s</comment>', $username));
170
        // Attach groups
171
        $groupOutput = [];
172
173
        foreach (explode(',', $groupOption) as $groupId) {
174
            if ((int) $groupId === 0) {
175
                foreach ($this->groups as $value) {
176
                    if ($groupId === $value->getName()) {
177
                        $group = $value;
178
179
                        break;
180
                    }
181
                }
182
            } else {
183
                $group = $this->groups[$groupId];
184
            }
185
186
            if (isset($group) && $group instanceof Group) {
187
                $groupOutput[] = $group->getName();
188
                $user->getGroups()->add($group);
189
            } else {
190
                throw new \RuntimeException('The selected group(s) can\'t be found.');
191
            }
192
        }
193
194
        // Set admin interface locale and enable password changed
195
        $user->setAdminLocale($locale);
196
        $user->setPasswordChanged(true);
197
198
        // Persist
199
        $this->userManager->updateUser($user);
200
        $output->writeln(sprintf('Added user <comment>%s</comment> to groups <comment>%s</comment>', $input->getArgument('username'), implode(',', $groupOutput)));
201
202
        return 0;
203
    }
204
205
    /**
206
     * Interacts with the user.
207
     *
208
     * @param InputInterface  $input  The input
209
     * @param OutputInterface $output The output
210
     *
211
     * @throws \InvalidArgumentException
212
     */
213
    protected function interact(InputInterface $input, OutputInterface $output)
214
    {
215 View Code Duplication
        if (!$input->getArgument('username')) {
0 ignored issues
show
Duplication introduced by
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...
216
            $question = new Question('Please choose a username:');
217
            $question->setValidator(function ($username) {
218
                if (null === $username) {
219
                    throw new \InvalidArgumentException('Username can not be empty');
220
                }
221
222
                return $username;
223
            });
224
            $username = $this->getHelper('question')->ask(
0 ignored issues
show
Bug introduced by
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...
225
                $input,
226
                $output,
227
                $question
228
            );
229
            $input->setArgument('username', $username);
230
        }
231
232 View Code Duplication
        if (!$input->getArgument('email')) {
0 ignored issues
show
Duplication introduced by
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...
233
            $question = new Question('Please choose an email:');
234
            $question->setValidator(function ($email) {
235
                if (null === $email) {
236
                    throw new \InvalidArgumentException('Email can not be empty');
237
                }
238
239
                return $email;
240
            });
241
            $email = $this->getHelper('question')->ask(
0 ignored issues
show
Bug introduced by
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...
242
                $input,
243
                $output,
244
                $question
245
            );
246
            $input->setArgument('email', $email);
247
        }
248
249
        if (!$input->getArgument('password')) {
250
            $question = new Question('Please choose a password:');
251
            $question->setHidden(true);
252
            $question->setHiddenFallback(false);
253
            $question->setValidator(function ($password) {
254
                if (null === $password) {
255
                    throw new \InvalidArgumentException('Password can not be empty');
256
                }
257
258
                return $password;
259
            });
260
            $password = $this->getHelper('question')->ask(
0 ignored issues
show
Bug introduced by
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...
261
                $input,
262
                $output,
263
                $question
264
            );
265
266
            $input->setArgument('password', $password);
267
        }
268
269
        if (!$input->getArgument('locale')) {
270
            $locale = $this->getHelper('question')->ask(
0 ignored issues
show
Bug introduced by
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...
271
                $input,
272
                $output,
273
                new Question('Please enter the locale (or leave empty for default admin locale):')
274
            );
275
            $input->setArgument('locale', $locale);
276
        }
277
278
        if (!$input->getOption('group')) {
279
            $question = new ChoiceQuestion(
280
                'Please enter the group(s) the user should be a member of (multiple possible, separated by comma):',
281
                $this->groups,
282
                ''
283
            );
284
            $question->setMultiselect(true);
285
            $question->setValidator(function ($groupsInput) {
286
                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...
287
                    throw new \RuntimeException('No user group(s) could be found');
288
                }
289
290
                // Validate that the chosen group options exist in the available groups
291
                $groupNames = array_unique(explode(',', $groupsInput));
292
                if (\count(array_intersect_key(array_flip($groupNames), $this->groups)) !== \count($groupNames)) {
293
                    throw new InvalidArgumentException('You have chosen non existing group(s)');
294
                }
295
296
                if ($groupsInput === '') {
297
                    throw new \RuntimeException('Group(s) must be of type integer and can not be empty');
298
                }
299
300
                return $groupsInput;
301
            });
302
303
            // Group has to be imploded because $input->setOption expects a string
304
            $groups = $this->getHelper('question')->ask($input, $output, $question);
0 ignored issues
show
Bug introduced by
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...
305
306
            $input->setOption('group', $groups);
307
        }
308
    }
309
}
310