Magento2 | PWA | GraphQL

Create Custom CLI command to create customers with supplied parameters Magento2


In this post we will check how to Create Custom CLI command in Magento2 and create customers with supplied parameters in that command arguments. 

You can find complete module on Github at Magelearn_CustomerCreateCommand



Let's start it by creating custom module.

Create folder inside app/code/Magelearn/CustomerCreateCommand

Add registration.php file in it:

1
2
3
4
5
6
7
<?php
 
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Magelearn_CustomerCreateCommand',
    __DIR__
);

Add composer.json file in it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
{
    "name": "magelearn/module-customer-create-command",
    "description": "Magento 2 Module which creates customer via command line interface with supplied parameters.",
    "type": "magento2-module",
    "require": {},
    "authors": [
        {
            "name": "vijay rami",
            "email": "vijaymrami@gmail.com"
        }
    ],
    "license": "proprietary",
    "minimum-stability": "dev",
    "autoload": {
        "files": [
            "registration.php"
        ],
        "psr-4": {
            "Magelearn\\CustomerCreateCommand\\": ""
        }
    }
}

Add etc/module.xml file in it:

1
2
3
4
<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Magelearn_CustomerCreateCommand" setup_version="1.0.0"/>
</config>

Now first we will add entry in di.xml file. To add command in Magento Command list.
Add file at etc/di.xml

1
2
3
4
5
6
7
8
9
10
<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Framework\Console\CommandList">
        <arguments>
            <argument name="commands" xsi:type="array">
                <item name="create_customer_command" xsi:type="object">Magelearn\CustomerCreateCommand\Console\Command\Create</item>
            </argument>
        </arguments>
    </type>
</config>

Now as per highlighted code above we will add our command list object file.
Add file at Console/Command/Create.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
<?php
 
namespace Magelearn\CustomerCreateCommand\Console\Command;
 
use Magento\Framework\App\State;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Magelearn\CustomerCreateCommand\Helper\Customer;
 
/**
 * Create Command class
 */
class Create extends Command
{
    /**
     * @var Customer
     */
    private $customerHelper;
 
    /**
     * @var State
     */
    private $state;
 
    /**
     * Create constructor.
     * @param Customer $customerHelper
     * @param State $state
     */
    public function __construct(
        Customer $customerHelper,
        State $state
    ) {
        $this->customerHelper = $customerHelper;
        $this->state = $state;
        parent::__construct();
    }
 
    /**
     * magelearn:customer:create
     *   [-f|--customer-firstname CUSTOMER-FIRSTNAME][REQUIRED]
     *   [-l|--customer-lastname CUSTOMER-LASTNAME][REQUIRED]
     *   [-e|--customer-email CUSTOMER-EMAIL][REQUIRED]
     *   [-p|--customer-password CUSTOMER-PASSWORD][REQUIRED]
     *   [-w|--website WEBSITE][REQUIRED]
     *   [-s|--send-email [SEND-EMAIL]][OPTIONAL]
     *   [-ns|--newsletter-subscribe [NEWSLETTER-SUBSCRIBE]][OPTIONAL]
     *
     * php bin/magento magelearn:customer:create -f "Vijay" -l "Rami" -e "vijay.rami@gmail.com" -p "test123" -w 1
     * php bin/magento magelearn:customer:create -f "Vijay" -l "Rami" -e "vijay.rami@gmail.com" -p "test123" -w 1 -s 1 --newsletter-subscribe 1
     * @param InputInterface $input
     * @param OutputInterface $output
     * @throws \Magento\Framework\Exception\LocalizedException
     * @return int|void|null
     *
     * Style the output text by using <error>, <info>, or <comment>
     */
    protected function execute(
        InputInterface $input,
        OutputInterface $output
    ) {
        $this->state->setAreaCode(\Magento\Framework\App\Area::AREA_GLOBAL);
        $output->writeln('<info>Creating new user</info>');
        $this->customerHelper->setData($input);
 
        $customer = $this->customerHelper->createCustomer();
         
        if ($customer && $customer->getId()) {
            $output->writeln("<info>Created new user</info>");
            $output->writeln((string) __("<comment>User ID: %1</comment>", $customer->getId()));
            $output->writeln((string) __("<comment>First name: %1</comment>", $customer->getFirstname()));
            $output->writeln((string) __("<comment>Last name: %1</comment>", $customer->getLastname()));
            $output->writeln((string) __("<comment>Email: %1</comment>", $customer->getEmail()));
            $output->writeln((string) __("<comment>Website Id: %1</comment>", $customer->getWebsiteId()));
            if ($input->getOption(Customer::KEY_NEWSLETTER_SUBSCRIBE)) {
                $output->writeln("<comment>Subscribed to Newsletter</comment>");
            }
            if ($input->getOption(Customer::KEY_SENDEMAIL)) {
                $output->writeln("<comment>Sending Email</comment>");
            }
        } else {
            $output->writeln("<error>Problem creating new user</error>");
            if ($e = $this->customerHelper->getException()) {
                $output->writeln((string) __("<error>%1</error>", $e->getMessage()));
            }
        }
    }
 
    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this->setName("magelearn:customer:create");
        $this->setDescription("Create new customer with supplied arguments");
        $this->setDefinition([
            new InputOption(Customer::KEY_FIRSTNAME, '-f', InputOption::VALUE_REQUIRED, '(Required) First name'),
            new InputOption(Customer::KEY_LASTNAME, '-l', InputOption::VALUE_REQUIRED, '(Required) Last name'),
            new InputOption(Customer::KEY_EMAIL, '-e', InputOption::VALUE_REQUIRED, '(Required) Email'),
            new InputOption(Customer::KEY_PASSWORD, '-p', InputOption::VALUE_REQUIRED, '(Required) Password'),
            new InputOption(Customer::KEY_WEBSITE, '-w', InputOption::VALUE_REQUIRED, '(Required) Website ID'),
            new InputOption(Customer::KEY_SENDEMAIL, '-s', InputOption::VALUE_OPTIONAL, '(Optional)(1/0) Send email (default 0)'),
            new InputOption(Customer::KEY_NEWSLETTER_SUBSCRIBE, '-ns', InputOption::VALUE_OPTIONAL, '(Optional)(1/0) Subscribe to Newsletter (default 0)')
        ]);
        parent::configure();
    }
}

Add Helper file at Helper/Customer.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
<?php
 
namespace Magelearn\CustomerCreateCommand\Helper;
 
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Api\Data\CustomerInterface;
use Magento\Customer\Api\Data\CustomerInterfaceFactory;
use Magento\Customer\Model\AccountConfirmation;
use Magento\Customer\Model\EmailNotificationInterface;
use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\App\Helper\Context;
use Magento\Framework\Encryption\EncryptorInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\MailException;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Input\Input;
 
/**
 * Customer Helper class
 */
class Customer extends AbstractHelper
{
    const KEY_EMAIL = 'customer-email';
    const KEY_FIRSTNAME = 'customer-firstname';
    const KEY_LASTNAME = 'customer-lastname';
    const KEY_PASSWORD = 'customer-password';
    const KEY_WEBSITE = 'website';
    const KEY_SENDEMAIL = 'send-email';
    const KEY_NEWSLETTER_SUBSCRIBE = 'newsletter-subscribe';
 
    /**
     * @var CustomerInterfaceFactory
     */
    private $customerInterfaceFactory;
 
    /**
     * @var CustomerRepositoryInterface
     */
    private $customerRepositoryInterface;
 
    /**
     * @var EncryptorInterface
     */
    private $encryptorInterface;
 
    /**
     * @var Symfony\Component\Console\Input\InputInterface
     */
    private $data;
 
    /**
     * @var Exception
     */
    private $exception;
 
    /**
     * @var LoggerInterface
     */
    private $logger;
 
    /**
     * @var EmailNotificationInterface
     */
    private $emailNotification;
 
    /**
     * @var AccountConfirmation
     */
    private $accountConfirmation;
 
    /**
     * @var EmailNotificationInterface
     */
    private $emailNotificationInterface;
 
    /**
     * Customer constructor.
     * @param Context $context
     * @param CustomerInterfaceFactory $customerInterfaceFactory
     * @param CustomerRepositoryInterface $customerRepositoryInterface
     * @param EncryptorInterface $encryptorInterface
     * @param LoggerInterface $logger
     * @param AccountConfirmation $accountConfirmation
     */
    public function __construct(
        Context $context,
        CustomerInterfaceFactory $customerInterfaceFactory,
        CustomerRepositoryInterface $customerRepositoryInterface,
        EncryptorInterface $encryptorInterface,
        LoggerInterface $logger,
        AccountConfirmation $accountConfirmation,
        EmailNotificationInterface $emailNotificationInterface
    ) {
        $this->customerInterfaceFactory = $customerInterfaceFactory;
        $this->customerRepositoryInterface = $customerRepositoryInterface;
        $this->encryptorInterface = $encryptorInterface;
        $this->logger = $logger;
        $this->accountConfirmation = $accountConfirmation;
        $this->emailNotificationInterface = $emailNotificationInterface;
        parent::__construct($context);
    }
 
    /**
     * @param Input $input
     */
    public function setData(Input $input)
    {
        $this->data = $input;
    }
 
    /**
     * Create Customer record
     * @return bool|\Magento\Customer\Api\Data\CustomerInterface
     */
    public function createCustomer()
    {
        $websiteId = $this->data->getOption(self::KEY_WEBSITE);
        $email = $this->data->getOption(self::KEY_EMAIL);
        $firstname = $this->data->getOption(self::KEY_FIRSTNAME);
        $lastname = $this->data->getOption(self::KEY_LASTNAME);
         
        try {
            if (!$websiteId || !$email || !$firstname || !$lastname) {
                throw new LocalizedException(__("One or more parameters missing"));
            }
 
            if (!\Zend_Validate::is(trim($firstname), 'NotEmpty')) {
                throw new LocalizedException(__("Invalid first name"));
            }
             
            if (!\Zend_Validate::is(trim($lastname), 'NotEmpty')) {
                throw new LocalizedException(__("Invalid last name"));
            }
 
            if (!\Zend_Validate::is(trim($email), 'EmailAddress')) {
                throw new LocalizedException(__("Invalid email address"));
            }
 
            if (!is_numeric($websiteId)) {
                throw new LocalizedException(__("Invalid website ID"));
            }
 
            $customer = $this->customerInterfaceFactory
                ->create()
                ->setWebsiteId((int) $websiteId)
                ->setEmail($email)
                ->setFirstname($firstname)
                ->setLastname($lastname);
         
            $hashedPassword = $this->encryptorInterface->getHash($this->data->getOption(self::KEY_PASSWORD), true);
             
            if ($this->data->getOption(self::KEY_NEWSLETTER_SUBSCRIBE)) {
                $extensionAttributes = $customer->getExtensionAttributes();
                $extensionAttributes->setIsSubscribed(true);
                $customer->setExtensionAttributes($extensionAttributes);
            }
             
            $customer = $this->customerRepositoryInterface->save($customer, $hashedPassword);
            if ($this->data->getOption(self::KEY_SENDEMAIL)) {
                $this->sendEmailConfirmation($customer, null, $hashedPassword);
            }
            $this->exception = false;
            return $customer;
        } catch (\Exception $e) {
            $this->logger->critical($e);
            $this->exception = $e;
            return false;
        }
    }
 
    /**
     * Send Email Confirmation
     * @param CustomerInterface $customer
     * @param string $redirectUrl
     * @param string $hash
     */
    protected function sendEmailConfirmation(CustomerInterface $customer, $redirectUrl = '', $hash = '')
    {
        try {
            $templateType = EmailNotificationInterface::NEW_ACCOUNT_EMAIL_REGISTERED;
            if ($this->isConfirmationRequired($customer) && $hash != '') {
                $templateType = EmailNotificationInterface::NEW_ACCOUNT_EMAIL_CONFIRMATION;
            } elseif ($hash == '') {
                $templateType = EmailNotificationInterface::NEW_ACCOUNT_EMAIL_REGISTERED_NO_PASSWORD;
            }
            $this->emailNotificationInterface->newAccount(
                $customer,
                $templateType,
                $redirectUrl,
                $customer->getStoreId()
            );
        } catch (MailException $e) {
            // If we are not able to send a new account email, this should be ignored
            $this->logger->critical($e);
        } catch (\UnexpectedValueException $e) {
            $this->logger->error($e);
        }
    }
 
    /**
     * Is confirmation required
     * @param $customer
     * @return bool
     */
    protected function isConfirmationRequired($customer)
    {
        return $this->accountConfirmation->isConfirmationRequired(
            $customer->getWebsiteId(),
            $customer->getId(),
            $customer->getEmail()
        );
    }
 
    /**
     * Get exception
     * @return Exception
     */
    public function getException()
    {
        return $this->exception;
    }
}

Related Post:

0 Comments On "Create Custom CLI command to create customers with supplied parameters Magento2 "

Back To Top