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

ChangePasswordCommand::interact()   B

Complexity

Conditions 6
Paths 8

Size

Total Lines 34

Duplication

Lines 34
Ratio 100 %

Importance

Changes 0
Metric Value
dl 34
loc 34
rs 8.7537
c 0
b 0
f 0
cc 6
nc 8
nop 2
1
<?php
2
3
namespace Kunstmaan\AdminBundle\Command;
4
5
use FOS\UserBundle\Model\UserManager as FOSUserManager;
6
use InvalidArgumentException;
7
use Kunstmaan\AdminBundle\Service\UserManager;
8
use Symfony\Component\Console\Command\Command;
9
use Symfony\Component\Console\Input\InputArgument;
10
use Symfony\Component\Console\Input\InputInterface;
11
use Symfony\Component\Console\Output\OutputInterface;
12
use Symfony\Component\Console\Question\Question;
13
14
final class ChangePasswordCommand extends Command
15
{
16
    protected static $defaultName = 'kuma:user:change-password';
17
18
    /** @var UserManager */
19
    private $userManager;
20
21 View Code Duplication
    public function __construct(/* UserManager */ $userManager)
0 ignored issues
show
Duplication introduced by
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...
22
    {
23
        parent::__construct();
24
25
        if (!$userManager instanceof UserManager && !$userManager instanceof FOSUserManager) {
26
            throw new InvalidArgumentException(sprintf('The "$userManager" argument must be of type "%s" or type "%s"', UserManager::class, FOSUserManager::class));
27
        }
28
        if ($userManager instanceof FOSUserManager) {
29
            // NEXT_MAJOR set the usermanaged typehint to the kunstmaan usermanager.
30
            @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 new Kunstmaan Usermanager %s.', __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...
31
        }
32
33
        $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...
34
    }
35
36
    protected function configure()
37
    {
38
        $this
39
            ->setDescription('Change the password of a user.')
40
            ->setDefinition([
41
                new InputArgument('username', InputArgument::REQUIRED, 'The username'),
42
                new InputArgument('password', InputArgument::REQUIRED, 'The password'),
43
            ])
44
            ->setHelp(<<<'EOT'
45
The <info>kuma:user:change-password</info> command changes the password of a user:
46
47
  <info>php %command.full_name% matthieu</info>
48
49
This interactive shell will first ask you for a password.
50
51
You can alternatively specify the password as a second argument:
52
53
  <info>php %command.full_name% matthieu mypassword</info>
54
55
EOT
56
            );
57
    }
58
59
    protected function execute(InputInterface $input, OutputInterface $output)
60
    {
61
        $username = $input->getArgument('username');
62
        $password = $input->getArgument('password');
63
64
        $user = $this->userManager->findUserByUsername($username);
65
66
        if (!$user) {
67
            throw new InvalidArgumentException(sprintf('User identified by "%s" username does not exist.', $username));
68
        }
69
70
        $user->setPlainPassword($password);
71
        $this->userManager->updateUser($user);
72
73
        $output->writeln(sprintf('Changed password for user <comment>%s</comment>', $username));
74
75
        return 0;
76
    }
77
78 View Code Duplication
    protected function interact(InputInterface $input, OutputInterface $output)
0 ignored issues
show
Duplication introduced by
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...
79
    {
80
        $questions = [];
81
82
        if (!$input->getArgument('username')) {
83
            $question = new Question('Please give the username:');
84
            $question->setValidator(function ($username) {
85
                if (empty($username)) {
86
                    throw new InvalidArgumentException('Username can not be empty');
87
                }
88
89
                return $username;
90
            });
91
            $questions['username'] = $question;
92
        }
93
94
        if (!$input->getArgument('password')) {
95
            $question = new Question('Please enter the new password:');
96
            $question->setValidator(function ($password) {
97
                if (empty($password)) {
98
                    throw new InvalidArgumentException('Password can not be empty');
99
                }
100
101
                return $password;
102
            });
103
            $question->setHidden(true);
104
            $questions['password'] = $question;
105
        }
106
107
        foreach ($questions as $name => $question) {
108
            $answer = $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...
109
            $input->setArgument($name, $answer);
110
        }
111
    }
112
}
113