Completed
Push — develop ( 3c1b70...55bb1b )
by Tom
03:03
created

ChangePasswordCommand::execute()   C

Complexity

Conditions 11
Paths 9

Size

Total Lines 60

Duplication

Lines 5
Ratio 8.33 %

Importance

Changes 0
Metric Value
dl 5
loc 60
rs 6.726
c 0
b 0
f 0
cc 11
nc 9
nop 2

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace N98\Magento\Command\Customer;
4
5
use Exception;
6
use Magento\Framework\App\Area;
7
use Symfony\Component\Console\Input\InputArgument;
8
use Symfony\Component\Console\Input\InputInterface;
9
use Symfony\Component\Console\Output\OutputInterface;
10
use Symfony\Component\Console\Question\Question;
11
12
/**
13
 * Class ChangePasswordCommand
14
 * @package N98\Magento\Command\Customer
15
 */
16
class ChangePasswordCommand extends AbstractCustomerCommand
17
{
18
    /**
19
     * @var \Magento\Framework\App\State
20
     */
21
    private $state;
22
23
    /**
24
     * @var \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository
25
     */
26
    private $customerRepository;
27
28
    /**
29
     * @var \Magento\Customer\Model\ResourceModel\Customer
30
     */
31
    private $customerResource;
32
33
    /**
34
     * @var \Magento\Customer\Model\CustomerRegistry $customerRegistry
35
     */
36
    private $customerRegistry;
37
38
    /**
39
     * @var \Magento\Framework\Encryption\EncryptorInterface
40
     */
41
    private $encryptor;
42
43
    protected function configure()
44
    {
45
        $this
46
            ->setName('customer:change-password')
47
            ->addArgument('email', InputArgument::OPTIONAL, 'Email')
48
            ->addArgument('password', InputArgument::OPTIONAL, 'Password')
49
            ->addArgument('website', InputArgument::OPTIONAL, 'Website of the customer')
50
            ->setDescription('Changes the password of a customer.');
51
52
        $help = <<<HELP
53
- Website parameter must only be given if more than one websites are available.
54
HELP;
55
        $this->setHelp($help);
56
    }
57
58
    /**
59
     * @param \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository
60
     * @param \Magento\Customer\Model\CustomerRegistry $customerRegistry
61
     * @param \Magento\Framework\Encryption\EncryptorInterface $encryptor
62
     */
63
    public function inject(
64
        \Magento\Framework\App\State $state,
65
        \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository,
66
        \Magento\Customer\Model\ResourceModel\Customer $customerResource,
67
        \Magento\Customer\Model\CustomerRegistry $customerRegistry,
68
        \Magento\Framework\Encryption\EncryptorInterface $encryptor
69
    ) {
70
        $this->state = $state;
71
        $this->customerRepository = $customerRepository;
72
        $this->customerResource = $customerResource;
73
        $this->customerRegistry = $customerRegistry;
74
        $this->encryptor = $encryptor;
75
    }
76
77
    /**
78
     * @param InputInterface $input
79
     * @param OutputInterface $output
80
     * @return int|void
81
     * @throws \Exception
82
     */
83
    protected function execute(InputInterface $input, OutputInterface $output)
84
    {
85
        $this->detectMagento($output);
86
        if ($this->initMagento()) {
87
            $questionHelper = $this->getHelperSet()->get('question');
88
            $email = $this->getHelper('parameter')->askEmail($input, $output);
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 askEmail() does only exist in the following implementations of said interface: N98\Util\Console\Helper\ParameterHelper.

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...
89
90
            // Password
91
            $password = $input->getArgument('password');
92 View Code Duplication
            if ($password === null) {
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...
93
                $question = new Question('<question>Password:</question>');
94
                $question->setHidden(true);
95
                $password = $questionHelper->ask($input, $output, $question);
96
            }
97
98
            $website = $this->getHelper('parameter')->askWebsite($input, $output);
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 askWebsite() does only exist in the following implementations of said interface: N98\Util\Console\Helper\ParameterHelper.

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...
99
100
            $changePassword = function () use ($email, $website, $password) {
101
                // @see \Magento\Framework\Session\SessionManager::isSessionExists Hack to prevent session problems
102
                @session_start();
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...
103
104
                // Fix for proxy which does not respect "emulateAreaCode".
105
                /** @var \Magento\Theme\Model\View\Design $design */
106
                $design = $this->getObjectManager()->get(\Magento\Theme\Model\View\Design::class);
107
                $design->setArea('frontend');
108
109
                $customer = $this->customerRegistry->retrieveByEmail($email, $website->getId());
110
                $passwordHash = $this->encryptor->getHash($password, true);
111
112
                if ($customer->getId()) {
113
                    $customerSecure = $this->customerRegistry->retrieveSecureData($customer->getId());
114
115
                    $customer->setRpToken($passwordHash ? null : $customerSecure->getRpToken());
116
                    $customer->setRpTokenCreatedAt($passwordHash ? null : $customerSecure->getRpTokenCreatedAt());
117
                    $customer->setPasswordHash($passwordHash ?: $customerSecure->getPasswordHash());
118
119
                    $customer->setFailuresNum($customerSecure->getFailuresNum());
120
                    $customer->setFirstFailure($customerSecure->getFirstFailure());
121
                    $customer->setLockExpires($customerSecure->getLockExpires());
122
                } elseif ($passwordHash) {
123
                    $customer->setPasswordHash($passwordHash);
124
                }
125
126
                $this->customerResource->save($customer);
127
128
                if ($passwordHash && $customer->getId()) {
129
                    $this->customerRegistry->remove($customer->getId());
130
                }
131
            };
132
133
            try {
134
                $this->state->setAreaCode(Area::AREA_FRONTEND);
135
                $this->state->emulateAreaCode(Area::AREA_FRONTEND, $changePassword);
136
137
                $output->writeln('<info>Password successfully changed</info>');
138
            } catch (Exception $e) {
139
                $output->writeln('<error>' . $e->getMessage() . '</error>');
140
            }
141
        }
142
    }
143
}
144