Completed
Push — develop ( 2a440e...d14017 )
by Christian
02:31
created

CreateCommand::getAdditionalFields()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 19
rs 9.6333
c 0
b 0
f 0
cc 4
nc 4
nop 1
1
<?php
2
3
namespace N98\Magento\Command\Customer;
4
5
use Magento\Customer\Api\AccountManagementInterface;
6
use Magento\Framework\App\State\Proxy as AppState;
7
use Magento\Framework\Exception\LocalizedException;
8
use N98\Util\Console\Helper\Table\Renderer\RendererFactory;
9
use Symfony\Component\Console\Helper\QuestionHelper;
10
use Symfony\Component\Console\Input\InputArgument;
11
use Symfony\Component\Console\Input\InputInterface;
12
use Symfony\Component\Console\Input\InputOption;
13
use Symfony\Component\Console\Output\OutputInterface;
14
use Symfony\Component\Console\Question\Question;
15
16
/**
17
 * Class CreateCommand
18
 * @package N98\Magento\Command\Customer
19
 */
20
class CreateCommand extends AbstractCustomerCommand
21
{
22
    /**
23
     * @var AccountManagementInterface
24
     */
25
    private $accountManagement;
26
27
    /**
28
     * @var AppState
29
     */
30
    private $appState;
31
32 View Code Duplication
    protected function configure()
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...
33
    {
34
        $this
35
            ->setName('customer:create')
36
            ->addArgument('email', InputArgument::OPTIONAL, 'Email')
37
            ->addArgument('password', InputArgument::OPTIONAL, 'Password')
38
            ->addArgument('firstname', InputArgument::OPTIONAL, 'Firstname')
39
            ->addArgument('lastname', InputArgument::OPTIONAL, 'Lastname')
40
            ->addArgument('website', InputArgument::OPTIONAL, 'Website')
41
            ->addArgument('additionalFields', InputArgument::IS_ARRAY, 'Additional fields, specifiy as field_name1 value2 field_name2 value2')
42
            ->addOption(
43
                'format',
44
                null,
45
                InputOption::VALUE_OPTIONAL,
46
                'Output Format. One of [' . implode(',', RendererFactory::getFormats()) . ']'
47
            )
48
            ->setDescription('Creates a new customer/user for shop frontend.');
49
    }
50
51
    /**
52
     * @param AccountManagementInterface $accountManagement
53
     * @param AppState $appState
54
     */
55
    public function inject(
56
        AccountManagementInterface $accountManagement,
57
        AppState $appState
58
    ) {
59
        $this->accountManagement = $accountManagement;
60
        $this->appState = $appState;
61
    }
62
63
    /**
64
     * @param InputInterface $input
65
     * @param OutputInterface $output
66
     * @return int
67
     * @throws \Exception
68
     */
69
    protected function execute(InputInterface $input, OutputInterface $output)
70
    {
71
        $this->detectMagento($output, true);
72
        if (!$this->initMagento()) {
73
            return 1;
74
        }
75
76
        /** @var QuestionHelper $questionHelper */
77
        $questionHelper = $this->getHelperSet()->get('question');
78
79
        // Email
80
        $email = $this->getHelperSet()->get('parameter')->askEmail($input, $output);
81
82
        // Password
83
        $password = $input->getArgument('password');
84 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...
85
            $question = new Question('<question>Password:</question> ');
86
            $question->setHidden(true);
87
            $password = $questionHelper->ask($input, $output, $question);
88
        }
89
90
        // Firstname
91
        $firstname = $input->getArgument('firstname');
92 View Code Duplication
        if ($firstname === 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>Firstname:</question> ');
94
            $firstname = $questionHelper->ask($input, $output, $question);
95
        }
96
97
        // Lastname
98
        $lastname = $input->getArgument('lastname');
99 View Code Duplication
        if ($lastname === 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...
100
            $question = new Question('<question>Lastname:</question> ');
101
            $lastname = $questionHelper->ask($input, $output, $question);
102
        }
103
104
        $website = $this->getHelperSet()->get('parameter')->askWebsite($input, $output);
105
106
        try {
107
            $additionalFields = $this->getAdditionalFields($input);
108
        } catch (\Exception $e) {
109
            $output->writeln('<error>' . $e->getMessage() . '</error>');
110
            return 1;
111
        }
112
113
        // create new customer
114
        $customer = $this->getCustomer();
115
        $customer->setWebsiteId($website->getId());
116
        $customer->loadByEmail($email);
117
118
        $customer->addData($additionalFields);
119
120
        $outputPlain = $input->getOption('format') === null;
121
122
        $table = [];
123
124
        $isError = false;
125
126
        if (!$customer->getId()) {
127
            $customer->setWebsiteId($website->getId());
128
            $customer->setEmail($email);
129
            $customer->setFirstname($firstname);
130
            $customer->setLastname($lastname);
131
            $customer->setStoreId($website->getDefaultGroup()->getDefaultStore()->getId());
132
133
            try {
134
                $this->appState->setAreaCode('frontend');
135
                $this->appState->emulateAreaCode(
136
                    'frontend',
137
                    [$this, 'createCustomer'],
138
                    [$customer, $password]
139
                );
140
141
                if ($outputPlain) {
142
                    $output->writeln(
143
                        sprintf(
144
                            '<info>Customer <comment>%s</comment> successfully created</info>',
145
                            $email
146
                        )
147
                    );
148
                } else {
149
                    $table[] = [
150
                        $email,
151
                        $password,
152
                        $firstname,
153
                        $lastname,
154
                    ];
155
                }
156
            } catch (\Exception $e) {
157
                $isError = true;
158
                $output->writeln('<error>' . $e->getMessage() . '</error>');
159
            }
160
        } elseif ($outputPlain) {
161
            $output->writeln('<warning>Customer ' . $email . ' already exists</warning>');
162
        }
163
164
        if (!$outputPlain) {
165
            $this->getHelper('table')
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 setHeaders() does only exist in the following implementations of said interface: N98\Util\Console\Helper\TableHelper.

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...
166
                ->setHeaders(['email', 'password', 'firstname', 'lastname'])
167
                ->renderByFormat($output, $table, $input->getOption('format'));
168
        }
169
170
        return $isError ? 1 : 0;
171
    }
172
173
    /**
174
     * @param string $customer
175
     * @param string $password
176
     * @throws \Magento\Framework\Exception\LocalizedException
177
     */
178
    public function createCustomer($customer, $password)
179
    {
180
        try {
181
            // Fix for proxy which does not respect "emulateAreaCode".
182
183
            // @see \Magento\Framework\Session\SessionManager::isSessionExists Hack to prevent session problems
184
            @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...
185
186
            /** @var \Magento\Theme\Model\View\Design $design */
187
            $design = $this->getObjectManager()->get(\Magento\Theme\Model\View\Design::class);
188
            $design->setArea('frontend');
189
            $this->accountManagement->createAccount(
190
                $customer->getDataModel(),
0 ignored issues
show
Bug introduced by
The method getDataModel cannot be called on $customer (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
191
                $password
192
            );
193
        } catch (LocalizedException $e) {
0 ignored issues
show
Bug introduced by
The class Magento\Framework\Exception\LocalizedException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
194
            if ($e->getRawMessage() !== 'Design config must have area and store.') {
195
                throw $e;
196
            }
197
        }
198
    }
199
200
    private function getAdditionalFields($input)
201
    {
202
        $additionalFields = $input->getArgument('additionalFields');
203
204
        if (count($additionalFields) == 0) {
205
            return [];
206
        }
207
208
        if (count($additionalFields) % 2 !== 0) {
209
            throw new \Exception('Additional fields must be formated as name1 value2 name2 value2, uneven paramater count specified');
210
        }
211
212
        $result = [];
213
        foreach (range(0, count($additionalFields) / 2 - 1) as $index) {
214
            $result[$additionalFields[$index * 2]] = $additionalFields[$index * 2 + 1];
215
        }
216
217
        return $result;
218
    }
219
}
220